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, in:
<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>
Out:
{
"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;
});
other than that, you might want to look at serialize();
You are all not fully correct. You cannot write:
Because this way if you have multiselect list - its values will be overwritten with the last one, since it's transmitted as: "param1" : "value1", "param1" : "value2".
So, correct approach is:
Here is a nice vanilla JS function I wrote to extract form data as an object. It also has options for inserting additions into the object, and for clearing the form input fields.
Here is an example of its use with a post request:
I use this:
jQuery Plugin
HTML Form
Get the Data
This method should do it. It serializes the form data and then converts them to an object. Takes care of groups of checkboxes as well.
It will fix issue:couldn't work with multiselects.