Skip to content

Instantly share code, notes, and snippets.

@paulirish
Created March 4, 2011 07:18
Show Gist options
  • Save paulirish/854293 to your computer and use it in GitHub Desktop.
Save paulirish/854293 to your computer and use it in GitHub Desktop.
jQuery unserialize Form plugin
// Unserialize (to) form plugin - by Christopher Thielen
// adapted and desuckified (a little) by Paul Irish
// takes a GET-serialized string, e.g. first=5&second=3&a=b and sets input tags (e.g. input name="first") to their values (e.g. 5)
(function($) {
$.fn.unserializeForm = function(values) {
if (!values) {
return this;
}
values = values.split("&");
var serialized_values = [];
$.each(values, function() {
var properties = this.split("=");
if ((typeof properties[0] != 'undefined') && (typeof properties[1] != 'undefined')) {
serialized_values[properties[0].replace(/\+/g, " ")] = properties[1].replace(/\+/g, " ");
}
});
values = serialized_values;
$(this).find(":input").removeAttr('checked').each(function() {
var tag_name = $(this).attr("name");
if (values[tag_name] !== undefined) {
if ($(this).attr("type") == "checkbox") {
$(this).attr("checked", "checked");
} else {
$(this).val(values[tag_name]);
}
}
})
}
})(jQuery);
@sorrx
Copy link

sorrx commented Aug 7, 2012

quick hack, because my form had radio-buttons - certainly not the best method - but it works for me
else if ($(this).attr("type") == "radio") { $('input:radio[name="'+tag_name+'"][value="'+values[tag_name]+'"]').attr("checked",true); }

@ishener
Copy link

ishener commented May 8, 2013

There is a problem with special charachters that doesn't get really "unserialized", for example '@'
What is did is changed line 34 to this:
$(this).val( decodeURIComponent(values[tag_name]) );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment