JavaScript - populate drop down list with array
You'll need to loop through your array elements, create a new DOM node for each and append it to your object:
var select = document.getElementById("selectNumber");
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);
}
<select id="selectNumber">
<option>Choose a number</option>
</select>
You can also do it with jQuery:
var options = ["1", "2", "3", "4", "5"];
$('#select').empty();
$.each(options, function(i, p) {
$('#select').append($('<option></option>').val(p).html(p));
});
I used Alex Turpin's solution with small corrections as mentioned below:
var select = document.getElementById("selectNumber");
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.text = opt;
el.value = opt;
select.add(el);
}
Corrections because with the appendChild()
function it loads when the DOM prepares. So It's not working in old (8 or lesser) IE versions. So with the corrections it's working fine.
Some notes on the differences between add()
and appendChild()
.
I found this also works...
var select = document.getElementById("selectNumber");
var options = ["1", "2", "3", "4", "5"];
// Optional: Clear all existing options first:
select.innerHTML = "";
// Populate list with options:
for(var i = 0; i < options.length; i++) {
var opt = options[i];
select.innerHTML += "<option value=\"" + opt + "\">" + opt + "</option>";
}
You'll first get the dropdown element from the DOM, then loop through the array, and add each element as a new option in the dropdown like this:
var myArray = new Array("1", "2", "3", "4", "5");
// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");
// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
// Append the element to the end of Array list
dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}
<form id="myForm">
<select id="selectNumber">
<option>Choose a number</option>
</select>
</form>
This assumes that you're not using JQuery, and you only have the basic DOM API to work with.