Skip to content

Instantly share code, notes, and snippets.

@pdxjohnny
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pdxjohnny/87d289579a3688dc58e5 to your computer and use it in GitHub Desktop.
Save pdxjohnny/87d289579a3688dc58e5 to your computer and use it in GitHub Desktop.
Handy jquery addtions
// Creates an object from a form
$.fn.toObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
// Populates a form from an object
$.fn.fromObject = function(obj)
{
for (var prop in obj)
{
var find = "[name='" + prop + "']";
if ($(this).find(find)[0])
{
$(this).find(find).val(obj[prop])
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment