I have a form on my site like this:
<form id="myform" action="" method="">
<input type="text" name="name[1][first]">
<input type="text" name="name[2][first]">
<input type="text" name="name[3][first]">
</form>
I want to simply grab all the data and send it to a webservice so have this js:
$fields = $('#myform').serializeArray();
Problem is, it creates the json with all the brackets shown in the input names so I get a parse error.
How can I use serializeArray and get proper json?
The resulting format that I would like to see is something like this:
{
"name": {
"1": {
"first": "val1"
},
"2": {
"first": "val2"
},
"3": {
"first": "val3"
}
}
}
Thanks!
I made a recursive function/plugin to do exactly this:
You can also call it on other selectors besides the entire
form
. For example, calling:$('input[name^="name\\["]').serializeControls()
will return an object containing only the
name
fields. See http://codepen.io/alexweissman/pen/MyWZdN for more examples.Please note that (for now), this will not work for field names with empty brackets (for example, fields like
input name="potatoes[]"
will be ignored because a unique key cannot be extracted).Here is a version of alexw code that works for field names with empty brackets. This allow you to manage fields with multiple values (checkboxes, select multiple).
Given that you have successfully serialized the array to
$fields
, you can now walk through it and convert it into a more easily digestable result object:While
$fields
is a valid name for a global variable, I can't bare to keep silent on this matter: in JavaScript, local variables are defined withvar
keyword and they don't have dollar sign before them - dollar sign usually refers to jQuery object. As a result you can fetch the fields by invoking: