I have this little utility/helper which serializes a form into a javaScript object
$.fn.serializeObject = function(fn) {
var o = {},
a = this.serializeArray(),
that;
$.each(a, function() {
that = this;
if($.isFunction(fn)){
that = fn(that.name, that.value);
}
if(o[this.name] !== undefined) {
val = that.value || '';
if(!o[that.name].push) {
o[that.name] = [o[that.name]];
}
o[that.name].push(that.value);
} else {
o[that.name] = that.value;
}
});
return o;
};
A typical usage of this plugin will be:
someNameSpace = {
//...
processForm: function (form) {
return JSON.stringify(form.serializeObject(function (key, val) {
return {
name: key,
value: encodeURIComponent(val)
};
}));
}
//...
};
Any suggestions on how to improve this piece of code?
See original gist