Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get form data with JavaScript/jQuery?

Is there a simple, one-line way to get the data of a form as it would be if it was to be submitted in the classic HTML-only way?

For example:

<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> </form> 

Output:

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

Something like this is too simple, since it does not (correctly) include textareas, selects, radio buttons and checkboxes:

$("#form input").each(function () {     data[theFieldName] = theFieldValue; }); 
like image 370
Bart van Heukelom Avatar asked Feb 16 '10 21:02

Bart van Heukelom


People also ask

How do I retrieve data from a form?

How to retrieve form data sent via GET. When you submit a form through the GET method, PHP provides a superglobal variable, called $_GET. PHP uses this $_GET variable to create an associative array with keys to access all the sent information ( form data ). The keys is created using the element's name attribute values.

What is FormData () in jQuery?

The jQuery Ajax formData is a method to provide form values like text, number, images, and files and upload on the URL sever. The jQuery Ajax formData is a function to create a new object and send multiple files using this object.


2 Answers

Use $('form').serializeArray(), which returns an array:

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

Other option is $('form').serialize(), which returns a string:

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

Take a look at this jsfiddle demo

like image 136
Paul Avatar answered Sep 28 '22 17:09

Paul


$('form').serialize() //this produces: "foo=1&bar=xxx&this=hi" 

demo

like image 29
chelmertz Avatar answered Sep 28 '22 19:09

chelmertz