[英]add options to drop down list with javascript
I need to add options to a drop down list. 我需要将选项添加到下拉列表中。 I have an array with the options that I need in the drop down list, but I'm not sure how to append the array to the list
我在下拉列表中有一个带有所需选项的数组,但是我不确定如何将数组追加到列表中
var productList = document.getElementById("selectFood");
var foodOption = document.createElement("option");
foodOption.textContent = [{
option1: "Meat Lovers"
}, {
option2: "Buffalo Wings"
}, {
option3: "margherita"
}, {
option4: "classic"
}];
for (i = 0; i < productList.length; i++) {
productList.appendChild(foodOption);
}
you can do with jquery, 你可以用jQuery做,
$.each(foodOption.textContent, function (i, value) {
$('#selectFood').append($('<option>').text(value).attr('value',value));
});
You need to create an option element. 您需要创建一个选项元素。
for (i = 0; i < foodOption.textContent.length; i++) {
var newElement = document.createElement('option');
newElement.innerHTML = foodOption.textContent[i];
productList.appendChild(newElement);
}
You have to make an array of string rather than array of objects 您必须创建一个字符串数组而不是对象数组
try this 尝试这个
foodOption.textContent = ["Meat Lovers" , "Buffalo Wings" , "margherita", "classic" ]
$.each(foodOption.textContent, function (index, value) {
$('#selectFood').append($('<option/>', { value: value, text: value }));
});
Try below code for your solution. 请尝试以下代码作为解决方案。
var productList = document.getElementById("selectFood");
var textContent = [{
option1: "Meat Lovers"
}, {
option2: "Buffalo Wings"
}, {
option3: "margherita"
}, {
option4: "classic"
}];
for(var iIntex in textContent) {
var foodOption = document.createElement("option");
var option=textContent[iIndex]["option"+(iIndex+1)];
foodOption.setAttribute("value",option);
foodOption.innerHTML=option;
productList.appendChild(foodOption);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.