Created
March 4, 2011 07:18
-
-
Save paulirish/854293 to your computer and use it in GitHub Desktop.
jQuery unserialize Form plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
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); }
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
Works nicely for me.
you're missing semicolons in line 37 + 38