Populate a form with a serialized data string using jQuery
OK, so you know about the great jQuery utility method serialize()
,
which, when applied to a jQuery object that represents a form, will turn all the
form data into a key/value serialized string. Randomly, I was asked if it was
possible to do the reverse. jQuery doesn’t have a method like that baked in, so
here’s my implementation.
function loadSerializedData(formId, data) { var tmp = data.split('&'), dataObj = {}; // Bust apart the serialized data string into an obj for (var i = 0; i < tmp.length; i++) { var keyValPair = tmp[i].split('='); dataObj[keyValPair[0]] = keyValPair[1]; } // Loop thru form and assign each HTML tag the appropriate value $('#' + formId + ' :input').each(function(index, element) { if (dataObj[$(this).attr('name')]) $(this).val(dataObj[$(this).attr('name')]); }); }
Is there a better way to do this? Let me know in the comments.
Comments
andy wrote on :
Looks good, but you could make it even better by setting it up as a chainable jQuery method that you could call against a form object: jQuery.fn.loadSerializedData(data) { ... } Replace references to formId with $(this) and then just call the method on a form object with: $('#myForm').loadSerializedData($myDataString);