Created
May 6, 2013 05:28
-
-
Save juliengrimault/5523508 to your computer and use it in GitHub Desktop.
serialize form to json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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