Spdexter
Spdexter

Reputation: 933

Populating dropdown by looping through an Array of objects

http://jsfiddle.net/5m86J/6/

returnLOB =[
    {
        id: 1,
        name:"CIB"
    },
    {
        id: 2,
        name:"GTI"
    }
]

The Above is the array of objects.I need to populate the below dropdown with options from array.

<div id="LOBSelect" class="clearfix displayOnCreate">
    <span class="label">Dropdown</span>
    <select name="lob-select" class="dk" id="lobSelect"></select>
</div>

The following loop only produces a dropdown with option form object [GTI] not the first one. Can anybody please tell me what is wrong here.

for (var j = 0; j < returnLOB.length; j++){
    $('#LOBSelect').find('select[name="lob-select"]').html($('<option/>', {
        value: returnLOB[j].name,
        text: returnLOB[j].name,
        id: returnLOB[j].id
    }));
}

Upvotes: 2

Views: 2061

Answers (4)

Mark Rijsmus
Mark Rijsmus

Reputation: 627

This could be done like this: http://jsfiddle.net/bX8nK/3/

var returnLOB = [{
    id: 1,
    name: "CIB"
}, {
    id: 2,
    name: "GTI"
}

]

$(returnLOB).each(function() {
    var lob = this;
    $('#LOBSelect select[name=lob-select]').append(
        $('<option/>', {
            value: lob.name,
            text: lob.name,
            id: lob.id
        })
    );
});

The .find() method which is called directly after the selector, could be made more efficient/readable by extending the selector itself.

Upvotes: 1

malkam
malkam

Reputation: 2355

Try this:

for (var i = 0; i < returnLOB .length; i++) {
                $("#lobSelect").append("<option id='"+returnLOB [i].Name+"' value='" + returnLOB [i].Name+ "'>" + result.results[i].Name + "</option>");
            }

Upvotes: -1

K K
K K

Reputation: 18099

Demo :http://jsfiddle.net/lotusgodkk/5m86J/7/

for (var j = 0; j < returnLOB.length; j++){
   $('#LOBSelect').find('select[name="lob-select"]').append($('<option/>', {
      value: returnLOB[j].name,
      text: returnLOB[j].name,
      id: returnLOB[j].id
  }));
}

Upvotes: 1

Satpal
Satpal

Reputation: 133433

You need to use .append() instead of .html()

Insert content, specified by the parameter, to the end of each element in the set of matched elements.

Code

$('#LOBSelect').find('select[name="lob-select"]').append($('<option/>', {
    value: returnLOB[j].name,
    text: returnLOB[j].name,
    id: returnLOB[j].id
}));

DEMO

Upvotes: 3

Related Questions