[英]Adding list of options to HTML5 select tag using JavaScript
I've the below HTML code, and need to update the "option" element dynamically, by a big list of elements coming back from the server 我有下面的HTML代码,并且需要通过从服务器返回的大量元素来动态更新“ option”元素
<select id='select'>
<option value = '0' selected></option>
</select>
So, I wrote the below JS code: 所以,我写了下面的JS代码:
var select = e.querySelector('#select');
for(var k=0; k<5;k++){
var opt = document.createElement('option');
opt.value=data[k].value;
opt.text=data[k].text;
select.add(opt);
}
I do not need to use JQuery or any other plugin. 我不需要使用JQuery或任何其他插件。
Is there a more neat and/or simpler way to do the same? 有没有更简洁和/或更简单的方法来做到这一点?
You can use the Option
constructor: 您可以使用
Option
构造函数:
var select = e.querySelector('#select');
for(var k=0; k<5;k++){
select.options.add(new Option(data[k].text, data[k].value));
}
Live example: 现场示例:
var data = [ {text: "Option 1", value: "1"}, {text: "Option 2", value: "2"}, {text: "Option 3", value: "3"}, {text: "Option 4", value: "4"}, {text: "Option 5", value: "5"} ]; var select = document.querySelector('#select'); for(var k=0; k<5;k++){ select.options.add(new Option(data[k].text, data[k].value)); }
<select id="select" size="10"></select>
Assuming data
is an array, you can also use Array#forEach
: 假设
data
是一个数组,您还可以使用Array#forEach
:
var select = e.querySelector('#select');
data.forEach(function(entry) {
select.options.add(new Option(entry.text, entry.value));
});
Live example: 现场示例:
var data = [ {text: "Option 1", value: "1"}, {text: "Option 2", value: "2"}, {text: "Option 3", value: "3"}, {text: "Option 4", value: "4"}, {text: "Option 5", value: "5"} ]; var select = document.querySelector('#select'); data.forEach(function(entry) { select.options.add(new Option(entry.text, entry.value)); });
<select id="select" size="10"></select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.