All to often when working with javascript you want to use javascript to get an object of key/value pairs of the form fields with javascript. The problem comes in when you have checkboxes and selects which accept multiple selections. In these situations its ideal to return an array of the values for one key. There are plugins that do this, but sometimes you just don’t want an entire plugin for one function. Well here’s how to do this:
var formvals = {};
jQuery.each(jQuery('#formid :input').serializeArray(),function(i,obj){
if (formvals[obj.name] == undefined)
formvals[obj.name] = obj.value;
else if (typeof formvals[obj.name] == Array)
formvals[obj.name].push(obj.value);
else formvals[obj.name] = [formvals[obj.name],obj.value];
});
From here it would be pretty easy to make this code into a jQuery function. Here’s what it might look like:
jQuery.fn.getFormValues = function(){
var formvals = {};
jQuery.each(jQuery(':input',this).serializeArray(),function(i,obj){
if (formvals[obj.name] == undefined)
formvals[obj.name] = obj.value;
else if (typeof formvals[obj.name] == Array)
formvals[obj.name].push(obj.value);
else formvals[obj.name] = [formvals[obj.name],obj.value];
});
return formvals;
}
So to call this booger we would only need to select the form we want to obtain the array from and call our function:
var myarr = $('#myform').getFormValues();
Easy as that!
Related posts:


One Response
Mike Jones
23|Dec|2010Hi Trent
Thanks for a very useful function.
I needed the getFormValues fn for a project I am working on but I found that for multiple checkboxes with the same name it created more than 1 array. This was because the test:
if (typeof formvals[obj.name] == Array) failed and so it created a second array.
I think it would have gone on to create additional arrays each with 2 elements in them if I had checked more boxes.
I replaced the line with:
if (typeof formvals[obj.name] != ‘string’) because it is either undefined, a string or an array.
Best wishes