Home > Article > Web Front-end > How can I retrieve form data using JavaScript/jQuery?
Retrieving Form Data with JavaScript/jQuery
Form submissions often require retrieving form data for validation or processing on the client side. This data includes input fields, select lists, and other elements. One common question is how to obtain this data in a simplified manner.
Using jQuery's serializeArray() Method
One elegant solution is to leverage the jQuery() method, which returns an array of objects representing the form data. This method effectively serializes the form into an array of key-value pairs:
$(function () { var formData = $('#form').serializeArray(); });
For example, if your form contains the following fields:
<input type="radio" name="foo" value="1" checked="checked" /> <input type="radio" name="foo" value="0" /> <input name="bar" value="xxx" /> <select name="this"> <option value="hi" selected="selected">Hi</option> <option value="ho">Ho</option> </select>
The output will be:
[ {"name":"foo","value":"1"}, {"name":"bar","value":"xxx"}, {"name":"this","value":"hi"} ]
Using jQuery's serialize() Method
Alternatively, you can use jQuery() to create a query string representation of the form data:
$(function () { var formData = $('#form').serialize(); });
This method outputs a string that contains key-value pairs separated by ampersands, suitable for submission to a server:
"foo=1&bar=xxx&this=hi"
Demonstration
View a practical demonstration of retrieving form data using both jQuery methods in this JSFiddle: https://jsfiddle.net/t7hvjne1/
The above is the detailed content of How can I retrieve form data using JavaScript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!