Santhosh Prabu Santhosh Prabu - 21 days ago 10
HTML Question

javascript two dropdown values from array

Simple doubt I am new to JavaScipt I want tho loop the array values in two dropdown list in HTML using script. But only one dropdown only working. If i comment the one another one working. I want to fill the values in both the drop down list. Whats the reason and 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