How to add option to select list in jQuery

danila dinan picture danila dinan · Nov 13, 2009 · Viewed 160.8k times · Source

My select list is called dropListBuilding. The following code does not seem to work:

 for (var i = 0; i < buildings.length; i++) {
     var val = buildings[i];
     var text = buildings[i];
     alert("value of builing at: " + i.toString() + " is: " + val);
     $("#dropListBuilding").addOption(val, text, false);
 }

This line dies:

$("#dropListBuilding").addOption(val, text, false);

What is the right to add items to the drop down in jQuery? I have tested without that line and the buildings variable does have my data element.

Answer

HaMinh Nguyen picture HaMinh Nguyen · Mar 30, 2012

Don't make your code so complicated. It can be done simply as below by using a foreach-like iterator:

$.each(buildings, function (index, value) {
    $('#dropListBuilding').append($('<option/>', { 
        value: value,
        text : value 
    }));
});