Question:
How can we efficiently extract form data in a similar manner to classic HTML form submissions? For instance, given a form with the following elements:
<form> <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> </form>
We want to obtain an output in the following JSON format:
{ "foo": "1", "bar": "xxx", "this": "hi" }
Answer:
To achieve this, we can utilize the $('form').serializeArray() function, which yields an array of objects where each object represents a form field and its value:
[ {"name":"foo","value":"1"}, {"name":"bar","value":"xxx"}, {"name":"this","value":"hi"} ]
Alternatively, we can use $('form').serialize(), which returns a string representing the form data:
"foo=1&bar=xxx&this=hi"
Check out this JSFiddle demo for a practical example: [JSFiddle Demo](https://jsfiddle.net/bmmvo79d/)
The above is the detailed content of How to Efficiently Extract Form Data with JavaScript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!