Skip to content

Instantly share code, notes, and snippets.

@nrioux
Created August 19, 2012 16:59
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 nrioux/3396254 to your computer and use it in GitHub Desktop.
Save nrioux/3396254 to your computer and use it in GitHub Desktop.
Convert form data to object with jQuery
(function($) {
$.fn.formData = function(this) {
var input = "input[name], select[name], textarea[name]";
if(this.is(input)) {
if(this.is("input[type='checkbox'], input[type='radio']")
return this.is(":checked") ? this.val() : undefined;
else if(this.is("input[type='number']"))
return Number(this.val());
else
return this.val();
} else if(this.is("form")) {
var data = {};
this.eq(0).find(input).not(":disabled")
.filter("[name$='[]']").each(function() { // convert [] fields to arrays like php
var name = $(this).attr("name");
name = name.substring(0, name.length - 2);
if(!data[name])
data[name] = [];
var val = $(this).formData();
if(val != undefined)
data[name].push(val);
}).end()
.not("[name$='[]']").each(function() {
var name = $(this).attr("name");
data[name] = $(this).formData() || data[name]; // if the name appears multiple times (eg for radio buttons), don't override a value with null
});
return data;
}
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment