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!