Hasan A Yousef
Hasan A Yousef

Reputation: 24908

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?

Upvotes: 0

Views: 2065

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

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>

Upvotes: 3

Related Questions