Skip to content

Instantly share code, notes, and snippets.

@imflop
Forked from shiawuen/LICENSE
Last active December 13, 2015 20:18
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 imflop/4968748 to your computer and use it in GitHub Desktop.
Save imflop/4968748 to your computer and use it in GitHub Desktop.
serialize form to json
/**
* Serialize form fields into 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 {
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