Home >Web Front-end >JS Tutorial >How to Access and Serialize Form Data with JavaScript/jQuery?
Accessing Form Data with JavaScript/jQuery
Retrieving form data as if it were submitted via the classic HTML method can be a common task in web development. To achieve this, JavaScript/jQuery provides two primary options:
Option 1: Using $('form').serializeArray()
This method converts the form data into an array of objects, with each object representing a form field. The output is in the following format:
[ {"name":"foo","value":"1"}, {"name":"bar","value":"xxx"}, {"name":"this","value":"hi"} ]
Option 2: Using $('form').serialize()
This method retrieves the form data as a string, formatted for submission via a POST request:
"foo=1&bar=xxx&this=hi"
Capturing Complex Form Elements
Unlike simple input fields, form elements like textareas, selects, radio buttons, and checkboxes require specific handling. Both methods mentioned above correctly handle complex form element data.
Example Usage
The following code demonstrates how to use the methods:
// Using serializeArray() var formDataArray = $('form').serializeArray(); // Using serialize() var formDataString = $('form').serialize();
Demonstration
Refer to this JSFiddle demo to see the methods in action: https://jsfiddle.net/
The above is the detailed content of How to Access and Serialize Form Data with JavaScript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!