[英]How to create a select drop-down using data from an array of objects in JavaScript?
I have an array of objects that I'd like to use to populate a Select option dropdown, but these elements do not already exist and must be created from scratch. 我有一个用于填充“选择”选项下拉列表的对象数组,但是这些元素尚不存在,必须从头开始创建。
I have working code using the createElement
method, but I can't use that method nor can I use options.add(new Option())
. 我有使用createElement
方法的工作代码,但是我不能使用该方法,也不能使用options.add(new Option())
。 How else can I create the select and option elements in the JavaScript? 我还可以如何在JavaScript中创建select和option元素?
var optionsList = [ { label: "Option 1", value: "option-1" }, { label: "Option 2", value: "option-2" }, { label: "Option 3", value: "option-3" } ]; if (optionsList.length == 0) { console.log("No data"); } else { var selectTag = document.createElement("SELECT"); document.body.appendChild(selectTag); for (var i = 0; i < optionsList.length; i++) { var option = optionsList[i]; selectTag.options.add(new Option(option.label, option.value)); } }
Instead of saying 而不是说
selectTag.options.add(new Option(...))
Simply create a new 'option' element and then add it to the select tag like this 只需创建一个新的“ option”元素,然后将其添加到select标记中,就像这样
optionsList.forEach(function(item, index, array) {
var opt = document.createElement("option");
opt.text = item.label;
opt.value = item.value;
selectTag.add(opt);
});
You can look at this link https://www.w3schools.com/jsref/met_select_add.asp for more info. 您可以查看此链接https://www.w3schools.com/jsref/met_select_add.asp以获取更多信息。
and a working example here https://jsfiddle.net/L5342j0y/ 这里还有一个工作示例https://jsfiddle.net/L5342j0y/
您可以只使用模板文字(比连接更简单,更简洁)制作一个字符串,并将其附加到select元素:
optionsList.forEach(e => selectTag.innerHTML += `<option value=${e.value}>${e.text}</option>`);
The following HTML and JavaScript shows how to add a Select and Options using data from an array of objects containing option labels and their values: 以下HTML和JavaScript显示了如何使用包含选项标签及其值的对象数组中的数据添加Select和Options:
<html>
<head>
<meta charset="utf-8">
<script src="app.js"></script>
</head>
<body onload="app()">
<p>Select your choice:</p>
<div id="div-id">
<!-- The select with data gets added here -->
</div>
</body>
</html>
app.js : app.js :
function app() {
var optionsList = [
{
label: "Option 1",
value: "option-1"
},
{
label: "Option 2",
value: "option-2"
},
{
label: "Option 3",
value: "option-3"
}
];
var selectTag = document.createElement("select");
for (let optObj of optionsList) {
let optEle = document.createElement("option");
optEle.text = optObj.label;
optEle.value = optObj.value;
selectTag.add(optEle);
}
var div = document.getElementById("div-id");
div.appendChild(selectTag);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.