Created
August 19, 2012 16:59
-
-
Save nrioux/3396254 to your computer and use it in GitHub Desktop.
Convert form data to object with jQuery
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.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