Search code examples
jqueryserializearray

serializeArray not working for selectbox


I am trying to convert form data to json and read the values of the fields that are modified upon clicking respective checkbox. This is working for text fields but not for select box. Can any one please take a look at the fiddle and help me read the select box(Headshot) value in "Person" tab.

$('#getDataBtn').click (function() {
     var data = $('#userForm').serializeArray();
     var pfId = 1234;
     var person=[];
    //  $.each(data, function(i, field){
    //     person[field.name] = field.value;            
    //  });
    //  personarray['Person']=person;
    //  console.log(JSON.stringify(personarray));
     var personObj = {};
     $.each(data, function(i, field){
        personObj = {};
        console.log(field.name);
        personObj['table name']= "Person";
        personObj['unique id']= "0";
        personObj['profile id']= pfId;
        personObj[field.name] = field.value;
        person.push(personObj)
    });
    personarray['Person']=person;
    console.log(JSON.stringify(personarray));  

});

https://jsfiddle.net/ycf6Ltad/5/


Solution

  • serializeArray() will take only those controls which will have name assigned to them. Since the dropdown doesn't have any name assigned, it was not listed.

    To correct, assign a name:

    <select class="form-control" id="sel1" name="sel1" disabled>
      <option>Yes</option>
      <option>No</option>
    </select>
    

    See this working fiddle.