DJB
DJB

Reputation: 11

How can I add an html option element dynamically to a select?

How can I dynamically add the option elements to the select using a for loop?

<select class="custom-select custom-select-lg mb-3">
  <option selected>Open this select menu</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

I have tried various forms of innerHTML but no luck.

Upvotes: 0

Views: 2502

Answers (2)

Fecosos
Fecosos

Reputation: 974

Adding options to select from an array?

html

<select name="select" id="select"></select>

javascript

var myOptions = ['one','two','three'];
var select = document.getElementById('select');
for (var i = 1; i <= myOptions.length; i++) {
    var option = '<option value="'+ i + '" >' + myOptions[i-1] + '</option>';
    select.insertAdjacentHTML( 'beforeend', option );
}

Upvotes: 4

hungersoft
hungersoft

Reputation: 531

This should do it. You can modify the code to fit in a loop and add your dynamic options.

var selectInnerHTML = document.getElementById('dynamic-select').innerHTML;
document.getElementById('dynamic-select').innerHTML = selectInnerHTML + '<option value="4">Four</option>';
<select id="dynamic-select" class="custom-select custom-select-lg mb-3">
  <option selected>Open this select menu</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

Upvotes: 0

Related Questions