0

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/

0

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.