OneMoreError
OneMoreError

Reputation: 7728

Unable to populate the drop down list options with values from an array

I want to populate a drop down list with a set of values, from 1,2,.... 100. Currently, I am doing this and its not working.

In the head section

<script type="text/javascript" src="./jquery-1.8.3.min.js"></script>
<script type="text/javascript">
    var select = document.getElementById("selectAge");
    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);
    }​
</script>

And, then in the form, I have

<label>Age</label>
<select id="selectAge"> 
    <option>Select your age</option>        
</select>

The drop down is not populated with a single value. I mean, I don't understand why its not happening. One correction might be to put the java script code just before the closing </body> tag, as its supposed to be populated only after the DOM is loaded. But I have even tried that and it does not work.

Upvotes: 0

Views: 1190

Answers (2)

Deprecated Darren
Deprecated Darren

Reputation: 895

<html>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        var selectAge = $("#selectAge"), 
        options = [1,2,3,4,5,6], 
        i;
        for ( i = 0; i < options.length; i++) {
            $(selectAge).append("<option value='" + options[i] + "'>" + options[i] + "</option>");
        }
    });
</script>
<body>
<lable>Age:</lable>
<select id="selectAge">
    <option>Select your age</option>
</select>
</body>
</html>

Upvotes: 1

Evan Davis
Evan Davis

Reputation: 36592

Works just fine in a fiddle. If you are using jQuery, wrap the whole thing in

$(function() { ... your code ...})` 

to wait until the DOM is ready.

Upvotes: 1

Related Questions