Getting Form Data with JavaScript/jQuery
When working with forms, there often arises a need to retrieve the data they contain programmatically. This data can be used for further processing, validation, or sending to a server. Fortunately, using JavaScript and jQuery, obtaining this data is a straightforward process.
jQuery's serializeArray() Method
One efficient and convenient method to obtain the data from a form is to use jQuery's serializeArray() method. This method returns an array of objects, where each object represents an input element in the form. Each object contains the element's name and value properties.
To use this method, simply invoke it on a form selector:
var data = $('form').serializeArray();
The data array will contain objects like the following:
[ {"name":"foo","value":"1"}, {"name":"bar","value":"xxx"}, {"name":"this","value":"hi"} ]
jQuery's serialize() Method
Another option is to use jQuery's serialize() method, which returns a string. This string represents the form data in the format accepted by a traditional HTML form submission.
To use this method, simply invoke it on a form selector:
var data = $('form').serialize();
The data variable will contain a string like the following:
"foo=1&bar=xxx&this=hi"
Demo
To see these methods in action, check out the following fiddle: https://jsfiddle.net/w84ny75L/
The above is the detailed content of How to Get Form Data Using JavaScript and jQuery?. For more information, please follow other related articles on the PHP Chinese website!