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
Mary-Kate OlsenOriginal
2024-12-01 08:42:14414browse

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>

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!

Statement:
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