user00239123
user00239123

Reputation: 278

Fill a <select> using JavaScript

So I want to add a dropdown in my form that will display numbers from 1 to 999 . I have tried to do it using JS but it doesn't work Here is what I have tried so far :

<html>
<head>
<script>
window.onload = fillDropDown(); 

function fillDropDown() { 
var ddl = document.getElementById( 'myDropdown' ); 
var theOption = new Option; 
var x; 
var i; 

for(i = 0; i < 999; i++) { 
x = i + 1; 
theOption.text = x; 
theOption.value = x; 
ddl.options[i] = theOption; 
} 
} 
</script>
</head>
<body>
<form id="myForm"> 
<select id="myDropdown"></select> 
</form>
</body>

But it doesn't work . Here is a jsfiddle example http://jsfiddle.net/j3nLxptn/

Upvotes: 0

Views: 55

Answers (2)

plalx
plalx

Reputation: 43718

The issue is that you are always reusing the same option element. You have to create a new Option instance at every iteration and that you can use add to actually append select options.

Also note that the Option constructor can take text and value parameters.

for (i = 0; i < 999; i++) {
    x = i + 1;
    ddl.add(new Option(x, x), null);
}

Upvotes: 0

Tot&#242;
Tot&#242;

Reputation: 1854

It works if you instantiate the option inside the loop:

 for (i = 0; i < 999; i++) {
        var theOption = new Option;
        x = i + 1;
        theOption.text = x;
        theOption.value = x;
        ddl.options[i] = theOption;
    }

See http://jsfiddle.net/j3nLxptn/1/

Upvotes: 3

Related Questions