Tuesday, January 19, 2010

Serialize Form to JSON

I came across a handy javascript function to serialize form to JSON, taken from here

$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
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;
};


add above script to your document, then if you are using jQuery you can just do something like the following:

$("form#data").serializeObject();


and as per need, simply use json2.js to convert the (JSON) form object into string:
JSON.stringify($("form#invite_users").serializeObject());

No comments:

Post a Comment