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.
Practical example
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.
// ONLINE-RUNNER:browser;
<html>
<body>
<form>
<select id="selectNumber">
<option>Select number</option>
</select>
</form>
<script>
var select = document.querySelector('#selectNumber');
var numbers = [1, 2, 3];
for (var i = 0; i < numbers.length; ++i) {
var option = numbers[i];
var element = document.createElement('option'); // creates option element
element.textContent = option; // sets option text
element.value = option; // sets option value
select.appendChild(element); // appends option element inside select
}
</script>
</body>
</html>