How to add option to select list in jQuery

2019-01-17 09:27发布

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.

8条回答
贪生不怕死
2楼-- · 2019-01-17 09:37

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 
    }));
});      
查看更多
▲ chillily
3楼-- · 2019-01-17 09:39

If you do not want to rely on the 3.5 kB plugin for jQuery or do not want to construct the HTML string while escapping reserved HTML characters, here is a simple way that works:

function addOptionToSelectBox(selectBox, optionId, optionText, selectIt)
{
    var option = document.createElement("option");
    option.value = optionId;
    option.text = optionText;
    selectBox.options[selectBox.options.length] = option;
    if (selectIt) {
        option.selected = true;
    }
}

var selectBox = $('#veryImportantSelectBox')[0];
addOptionToSelectBox(selectBox, "ID1", "Option 1", true);
查看更多
戒情不戒烟
4楼-- · 2019-01-17 09:39

For me this one worked

success: function(data){
            alert("SUCCCESS");
            $.each(data,function(index,itemData){
                console.log(JSON.stringify(itemData));
                $("#fromDay").append( new Option(itemData.lookupLabel,itemData.id) )
            });
        }
查看更多
Melony?
5楼-- · 2019-01-17 09:50

Your code fails because you are executing a method (addOption) on the jQuery object (and this object does not support the method)

You can use the standard Javascript function like this:

$("#dropListBuilding")[0].options.add( new Option("My Text","My Value") )
查看更多
Rolldiameter
6楼-- · 2019-01-17 09:51

This is working fine, try out this.

var ob = $("#myListBox");

for (var i = 0; i < buildings.length; i++) {
     var val = buildings[i];
     var text = buildings[i];

     ob.prepend("<option value="+ val +">" + text + "</option>");
}
查看更多
Emotional °昔
7楼-- · 2019-01-17 09:52

Doing it this way has always worked for me, I hope this helps.

var ddl = $("#dropListBuilding");   
for (k = 0; k < buildings.length; k++)
   ddl.append("<option value='" + buildings[k]+ "'>" + buildings[k] + "</option>");
查看更多
登录 后发表回答