EN
JavaScript - fill select element dropdown list with array
0 points
In this article, we would like to show you how to fill a select element dropdown list with an array using JavaScript.
In this example, we create a select
element with the first option only. Then inside a simple for
loop we dynamically create more option elements whose value
and textContent
properties are taken from the numbers
array.
xxxxxxxxxx
1
<html>
2
<body>
3
<form>
4
<select id="selectNumber">
5
<option>Select number</option>
6
</select>
7
</form>
8
<script>
9
10
var select = document.querySelector('#selectNumber');
11
12
var numbers = [1, 2, 3];
13
14
for (var i = 0; i < numbers.length; ++i) {
15
var option = numbers[i];
16
var element = document.createElement('option'); // creates option element
17
element.textContent = option; // sets option text
18
element.value = option; // sets option value
19
select.appendChild(element); // appends option element inside select
20
}
21
22
</script>
23
</body>
24
</html>