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())
. How else can I create the select and option elements in the JavaScript?
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
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.
and a working example here 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>
<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 :
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);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.