简体   繁体   中英

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

<select id='select'>
     <option value = '0' selected></option>
</select>

So, I wrote the below JS code:

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.

Is there a more neat and/or simpler way to do the same?

You can use the Option constructor:

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 :

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> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM