Home  >  Article  >  Web Front-end  >  How to retrieve form data as a JSON object using JavaScript/jQuery?

How to retrieve form data as a JSON object using JavaScript/jQuery?

Linda Hamilton
Linda HamiltonOriginal
2024-11-10 17:19:02875browse

How to retrieve form data as a JSON object using JavaScript/jQuery?

Retrieving Form Data with JavaScript/jQuery

When capturing form data, you may seek a straightforward approach that mirrors the traditional HTML-only submission method. Consider the following 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>

`

Your goal is to obtain the following JSON object from this form:

{
    "foo": "1",
    "bar": "xxx",
    "this": "hi"
}

However, oversimplified approaches like the following may not accurately capture all form elements (such as textareas, selects, radio buttons, and checkboxes):

$("#form input").each(function () {
    data[theFieldName] = theFieldValue;
});

Solution: $('form').serializeArray()

Fortunately, jQuery provides the $('form').serializeArray() method, which returns an array of objects containing the name and value of each form element:

[
  {"name":"foo","value":"1"},
  {"name":"bar","value":"xxx"},
  {"name":"this","value":"hi"}
]

Alternative Option: $('form').serialize()

If you prefer a string representation of the form data, you can use $('form').serialize(), which returns a URL-encoded string:

"foo=1&bar=xxx&this=hi"

For a live demonstration, refer to the provided jsfiddle demo.

The above is the detailed content of How to retrieve form data as a JSON object using 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