Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 226
Santhosh Prabu Avatar asked Nov 11 '16 08:11

Santhosh Prabu


People also ask

How can we select multiple values from dropdown?

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.

How do you populate values in one HTML dropdown list with another using simple JavaScript?

ready(function () { var list1 = document. getElementById('firstList'); list1. options[0] = new Option('--Select--', ''); list1. options[1] = new Option('Snacks', 'Snacks'); list1.

How can I give an array as options to select element?

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 .


1 Answers

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>
like image 56
VadimB Avatar answered Oct 12 '22 22:10

VadimB