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>
To select multiple options in a drop-down list, use the multiple properties. It allows you to select more than one option while pressing CTRL key.
ready(function () { var list1 = document. getElementById('firstList'); list1. options[0] = new Option('--Select--', ''); list1. options[1] = new Option('Snacks', 'Snacks'); list1.
To set a JavaScript array as options for a select element, we can use the options. add method and the Option constructor. to add the select drop down. to select the select element with querySelector .
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With