0

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?

2
  • I think thats the least you have to do without using any plugin. I would suggest you use for(var k in data). Commented Jun 13, 2016 at 7:04
  • 1
    @HarryBomrah: 1. No, it isn't. 2. for-in isn't for iterating arrays, more here. Commented Jun 13, 2016 at 7:08

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, it is perfect, I tried "new document.createElement('option');" but did not work, and thought it is silly to mention it :), thanks again.
It worked with both select.options.add, and select.add
@HasanAYousef: Huh, well look at that, HTMLSelectElement has an add. Interesting!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.