Home > Web Front-end > JS Tutorial > How to Efficiently Extract Form Data with JavaScript/jQuery?

How to Efficiently Extract Form Data with JavaScript/jQuery?

Mary-Kate Olsen
Release: 2024-12-01 08:42:14
Original
327 people have browsed it

How to Efficiently Extract Form Data with JavaScript/jQuery?

Retrieving Form Data with JavaScript/jQuery

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>
Copy after login

We want to obtain an output in the following JSON format:

{
    "foo": "1",
    "bar": "xxx",
    "this": "hi"
}
Copy after login

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"}
]
Copy after login

Alternatively, we can use $('form').serialize(), which returns a string representing the form data:

"foo=1&bar=xxx&this=hi"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template