JavaScript
Article

jQuery serializeArray() Function

By 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().

$('selector').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
	*/
});
})(jQuery);

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();
console.log(url);
//result action url + ? + param1 = value1  & param2 = value2 etc...
  • Nick

    I think it’s my fault, probably I’ve missed something, but I’m still asking why sometimes I could find the “TypeError: $(“:input”) is null”

  • jquery4u

    Hi Nick,
    Thanks for asking this! I have added the following to the post, hope it answers your question.

    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

    Cheers
    Sam

    • Nick

      thank you very much Sam

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.