Santhosh Prabu Santhosh Prabu - 22 days ago 6
HTML Question

Two dropdown values from an array using JavaScript

Simple question: I want to loop the array values in two dropdown lists in HTML using JavaScript. But only one dropdown is working. If I comment the one, the another one works. I want to fill the values in both the dropdown lists. What's wrong in this simple code?



var select = document.getElementById("selectNumber");
var select2 = document.getElementById("selectNumber2");
var options = ["1", "2", "3", "4", "5"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
select2.appendChild(el);
}

<select id="selectNumber">
<option>Choose a number</option>
</select>
<select id="selectNumber2">
<option>Choose a number</option>
</select>




Answer

Do not use the same element for both controls. Clone it first

    var select = document.getElementById("selectNumber");
    var select2 = document.getElementById("selectNumber2");
    var options = ["1", "2", "3", "4", "5"];
    for (var i = 0; i < options.length; i++) {
      var opt = options[i];
      var el = document.createElement("option");
      el.textContent = opt;
      el.value = opt;
      select.appendChild(el);
      select2.appendChild(el.cloneNode(true));
    }
<select id="selectNumber">
  <option>Choose a number</option>
</select>
<select id="selectNumber2">
  <option>Choose a number</option>
</select>

Comments