Alex Rivera | Logout

jquery serialize input with arrays

Asked 2012-06-20T19:58:48.353
15

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!

Edit
Report

1 Answer

0

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:

var result = {};
for(var i in $fields) {
   var parts = $fields[i].name.split("[");
   var resultIndex = parseInt(parts[1].replace(']', ''), 10);
   result[resultIndex] = $fields[i].value; 
}

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 with var 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:

var fields = $('#myform').serializeArray();
answered 2012-06-20T20:04:45.787

Your Answer