Skip to content

Instantly share code, notes, and snippets.

@juliengrimault
Created May 6, 2013 05:28
Show Gist options
  • Save juliengrimault/5523508 to your computer and use it in GitHub Desktop.
Save juliengrimault/5523508 to your computer and use it in GitHub Desktop.
serialize form to json
(function ($) {
$.fn.serializeJSON = function () {
var json = {}
var form = $(this);
form.find('input, select').each(function () {
var val
if (!this.name) return;
if ('radio' === this.type) {
if (json[this.name]) { return; }
json[this.name] = this.checked ? this.value : '';
} else if ('checkbox' === this.type) {
val = json[this.name];
if (!this.checked) {
if (!val) { json[this.name] = ''; }
} else {
json[this.name] =
typeof val === 'string' ? [val, this.value] :
$.isArray(val) ? $.merge(val, [this.value]) :
this.value;
}
} else {
if (this.value != "") {
json[this.name] = this.value;
}
}
})
return json;
}
})(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment