I have written some javascript code that’s supposed to put options into a select box. The select box’s code is below:
<select id="dayOfTheWeek" name="dayOfTheWeek"></select>
In my javascript coding, I have a method called populateDays that’s supposed to fill the select box with 7 options – one for each day of the week. The code for it is below:
function populateDays() {
var days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ];
var dayOfWeek = document.getElementById("dayOfTheWeek");
var today = (new Date()).getDay();
for (var i = 0; i < days.length; i++) {
var length = dayOfWeek.options.length;
dayOfWeek.add(new Option(days[i], i), length);
}
dayOfWeek.selectedIndex = today;
}
Later on in the script I make a call to this method. I know that the browser runs the javascript code when the browser loads because I put an alert() statement inside of the populateDays method and it appeared as I loaded the page.
populateDays();
For some reason, when I load the page, the select box is completely empty. Why does the populateDays() method not load that select box with the options?
Erm, it should work just fine. If it doesn’t:
Method 2 (jsFiddle example) –
innerHTMLMethod 3 – creating elements programmatically