如何在 jQuery 中添加选项来选择列表

我的选择列表称为 dropListBuilding。下面的代码似乎不起作用:

 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);
}

这句话结束了:

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

在 jQuery 中向下拉列表添加项的权利是什么?我已经测试了没有这条线和建筑物变量确实有我的数据元素。

171481 次浏览
$('#dropListBuilding').append('<option>'+val+'</option>');

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>");

It looks like you want this pluging as it follows your existing code, maybe the plug in js file got left out somewhere.

http://www.texotela.co.uk/code/jquery/select/

var myOptions = {
"Value 1" : "Text 1",
"Value 2" : "Text 2",
"Value 3" : "Text 3"
}
$("#myselect2").addOption(myOptions, false);
// use true if you want to select the added options » Run

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") )

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>");
}

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);

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
}));
});

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) )
});
}
$.each(data,function(index,itemData){
$('#dropListBuilding').append($("<option></option>")
.attr("value",key)
.text(value));
});