I been trying to have an array populate a drop down, I got this examples from this post: JavaScript - populate drop down list with array
I'm using this html:
<select id="selectNumber">
<option>Choose a number</option>
</select>
with this js
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);
}
But it only works if I place the js inside the HTML document, if I place it on a separate file it gives me this errror in Chrome:
>Uncaught TypeError: Cannot read property 'appendChild' of null at g.js:8
I also tryed this one but same thing happens:
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);
}
The code only works if I put it inside the HTML file but if i have it on a separate file it gives me that error.
Any idea why?