Search code examples
jqueryjsonserializearray

Jquery - SerializeArray() by ID


I have this problem, I use serializearray() jquery for serialize all fields of Form to Json. It works fine if in the input I put the name attribute, but if I'd like to put only the ID attribute It doesn't work.

The good function by name [name is similar: '#myformnameid']:

function formToJson(nameForm)
{
 var jsonForm={};
 var queryFrom = $(nameForm).serializeArray();

 for (i in queryFrom) {
   jsonForm[queryFrom[i].name] = queryFrom[i].value;
  }
 return jsonForm;
}

I tried for ID solution with attr.

function formToJson(nameForm)
{
 var jsonForm={};
 var queryFrom = $(nameForm).serializeArray();

 for (i in queryFrom) {
   jsonForm[queryFrom[i].attr("id")] = queryFrom[i].value;
  }
 return jsonForm;
}

Any Idea?


Solution

  • What serializeArray does is take the form input objects and converts them into an array of javascript objects. From the documentation, the form is similar to

    [
      {
        name: "a",
        value: "1"
      },
      {
        name: "b",
        value: "2"
      },
      {
        name: "c",
        value: "3"
      }    
    ]
    

    You can iterate over this array by name or value, like you're doing, and it will return the proper data.

    The problem you're having is that you're not iterating over the actual elements anymore, just the data from those elements. If you'd like to iterate over the elements, you'll need to do something like:

    function formToJson(nameForm)
    {
     var jsonForm={};
     $("input", $(nameForm)).each(function(index){
       jsonForm[$(this).attr("id")] = this.value;
     })
     return jsonForm;
    }