jQuery serializeArray() Function

Sam Deering

Hi guys, I thought I would do a quick post on this awesome function which can save you time if you need to create an array of form input elements and get their values.

jQuery .serializeArray() Syntax

jQuery .serializeArray() can be used to encode a set of form elements as an array of names and values. Note: only inputs with the “name” attribute present will be picked up by serializeArray().


jQuery .serializeArray() Basic Example

(function($) {
var fields = $(':input').serializeArray(); /*creates a JSON type array structure of name and value pairs*/
jQuery.each(fields, function (i, field) {
    console.log('input' + i + ': ' + field.name + " = " + field.value);
   /* output
	* input0: name = Enter your name
	* input1: email = Enter your email
	* input2: phone = Enter your phone
	* input3: message = Enter your message

Try out the code in Firebug on this form: http://www.jquery4u.com/contact/

Common Errors

If you are seeing this error: TypeError: $(“:input”) is null this may be because:

  • You need to specify the jQuery namespace because you are running more jQuery libraries (such as Mootools or Prototype). If you are unsure how to do this, read here: jQuery no conflict

Update: 16/07/2011: This script can be useful to create url params from a form:

$form = $('#formid');
var url = $form.attr('action') + '?' + $form.serialize();
//result action url + ? + param1 = value1  & param2 = value2 etc...