0

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.

wazz
  • 4,953
  • 5
  • 20
  • 34
DJB
  • 11
  • 1
  • I'm sure this has been answered before. And why do you need a for-loop? Be more specific. [Take the tour](https://stackoverflow.com/tour). – wazz Mar 24 '18 at 04:52
  • you didn't post the loop you mentioned – Circle Hsiao Mar 24 '18 at 05:10
  • Possible duplicate of [Adding options to select with javascript](https://stackoverflow.com/questions/8674618/adding-options-to-select-with-javascript) – Circle Hsiao Mar 24 '18 at 05:11

2 Answers2

4

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 );
}
Fecosos
  • 944
  • 7
  • 17
  • This works well for me. Guess I did not dig deep enough into html documentation to come across insertAdjacentHTML. – DJB Mar 24 '18 at 16:30
0

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>
hungersoft
  • 531
  • 4
  • 8