jQuery ajax - serializeArray() method

Example

Output the result of serializing form values in array form:

$("button").click(function(){
  x=$("form").serializeArray();
  $.each(x, function(i, field){
    $("#results").append(field.name + ":" + field.value + " ");
  );
);

Try It Yourself

Definition and Usage

serializeArray() method creates an object array (name and value) by serializing form values.

You can select one or more form elements (such as input and/or textarea), or the form element itself.

Syntax

$(selector).serializeArray()

Detailed Explanation

serializeArray() method serializes form elements (similar to .serialize() method), returning JSON data structure.

Note:This method returns a JSON object rather than a JSON string. You need to use a plugin or a third-party library for stringification.

The returned JSON object is an array of objects, each containing one or two name-value pairs - name parameter and value parameter (if the value is not empty). For example:

[ 
  {name: 'firstname', value: 'Hello'}, 
  {name: 'lastname', value: 'World'},
  {name: 'alias'}, // The value is empty
]

.serializeArray() method uses the W3C standard successful controlsto determine which elements should be included. It should be noted that elements cannot be disabled (disabled elements will not be included), and elements should have a name attribute. The value of the submit button will not be serialized. The data of file selection elements will also not be serialized.

This method can operate on objects of selected individual form elements, such as <input>, <textarea>, and <select>. However, a more convenient method is to directly select the <form> tag itself for serialization operations.

$("form").submit(function() {
  console.log($(this).serializeArray());
  return false;
);

The above code generates the following data structure (assuming the browser supports console.log):

[
  {
    name: a
    value: 1
  },
  {
    name: b
    value: 2
  },
  {
    name: c
    value: 3
  },
  {
    name: d
    value: 4
  },
  {
    name: e
    value: 5
  }
]

Example

Get form content and insert it into the web page:

HTML code:

<p id="results"><b>Results:</b> </p>
<form>
  <select name="single">
    <option>Single</option>
    <option>Single2</option>
  </select>
  <select name="multiple" multiple="multiple">
    <option selected="selected">Multiple</option>
    <option>Multiple2</option>
    <option selected="selected">Multiple3</option>
  </select><br/>
  <input type="checkbox" name="check" value="check1"/> check1
  <input type="checkbox" name="check" value="check2" checked="checked"/> check2
  <input type="radio" name="radio" value="radio1" checked="checked"/> radio1
  <input type="radio" name="radio" value="radio2"/> radio2
</form>

jQuery code:

var fields = $("select, :radio").serializeArray();
jQuery.each( fields, function(i, field){
  $("#results").append(field.value + " ");
);