Skip to main content

jQuery serializeArray() Function

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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...

Related Articles

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn the basics of programming with the web's most popular language - JavaScript


A practical guide to leading radical innovation and growth.

Integromat Tower Ad