I want to fill a dropdown list and I’ve written the following code:
<script language="JavaScript1.2">
window.onload = fillDropDown();
function fillDropDown() {
var ddl = document.getElementById("dia");
var theOption = new Option;
var x;
var i;
for(i = 1; i < 32; i++) {
x = i + 1;
theOption.text = x;
theOption.value = x;
ddl.options[i] = theOption;
}
}
</script>
<body>
<form>
<select id=dia></select>
</form>
<body>
It isn’t working, any idea why?
You have some errors in your code.
1. The first common mistake is the following:
This previous code is registering the result of the called function
fillDropDownand then assigning its results intowindow.onload. Thus, this will never do something. To register an event you have to assign a function not the result of a called function. The difference is this:2. Another mistake I found, is about the creation of the
optionelement. The better way to create HTML element in JavaScript is using the almost-standarddocument.createElementfunction.3. Also your HTML markup has an error. Your
selectis written:<select id=dia></dia>and it should be<select id="dia"></select>;So, with all theses changes highlighted the resulting code will be like this:
And it works like a charm. You can see it in action in this live demo: http://jsfiddle.net/dyjLS/
Note: I highly recommend to use a JavaScript library such as
jQueryto do this, since it will deal with almost all the cross-browser inconsistencies. If you use it, your code will look like the following:¡Voilà!