30

I have this JavaScript+HTML to populate a dropdown menu but it is not working, am i doing anything wrong? Note I want the drop down menu to be filled on page Load

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function addList(){
    var select = document.getElementById("year");
    for(var i = 2011; i >= 1900; --i) {
    var option = document.createElement('option');
    option.text = option.value = i;
    select.add(option, 0);
      }
     }
    </script>
    </head>

    <body>

       <select id="year" name="year"></select>
      
    </body>
    </html> 
2

5 Answers 5

32

Since your script is in <head>, you need to wrap it in window.onload:

window.onload = function () {
    var select = document.getElementById("year");
    for(var i = 2011; i >= 1900; --i) {
        var option = document.createElement('option');
        option.text = option.value = i;
        select.add(option, 0);
    }
};

You can also do it in this way

<body onload="addList()">
Sign up to request clarification or add additional context in comments.

Comments

16

For higher performance, I recommend this:

var select = document.getElementById("year");
var options = [];
var option = document.createElement('option');

//for (var i = 2011; i >= 1900; --i)
for (var i = 1900; i < 2012; ++i)
{
    //var data = '<option value="' + escapeHTML(i) +'">" + escapeHTML(i) + "</option>';
    option.text = option.value = i;
    options.push(option.outerHTML);
}

select.insertAdjacentHTML('beforeEnd', options.join('\n'));

This avoids a redraw after each appendChild, which speeds up the process considerably, especially for a larger number of options.

Optional for generating the string by hand:

function escapeHTML(str)
{
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}

However, I would not use these kind of methods at all.
It seems crude. You best do this with a documentFragment:

var docfrag = document.createDocumentFragment();

for (var i = 1900; i < 2012; ++i)
{
     docfrag.appendChild(new Option(i, i));
}

var select = document.getElementById("year");
select.appendChild(docfrag);

1 Comment

How about if I just want to replace the value instead of appending? How would I do that?
1

Try this

<script type="text/javascript">
    function AddItem()
    {
        // Create an Option object       
        var opt = document.createElement("option");        

        // Assign text and value to Option object
        opt.text = "New Value";
        opt.value = "New Value";

        // Add an Option object to Drop Down List Box
        document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
    }
<script />

The Value will append to the drop down list.

1 Comment

This actually worked! The other examples did not. Thank you! (implementation here:) if ($("#MainContent_ddlFilterFieldKey").val() == "Date Time") {// Create an Option object var opt = document.createElement("option"); // Assign text and value to Option object opt.text = "New Value"; opt.value = "New Value"; // Add an Option object to Drop Down List Box document.getElementById('MainContent_ddlFilterBooleanOption').options.add(opt); }
1

Try to use appendChild method:

select.appendChild(option);

Comments

0

i think you have only defined the function. you are not triggering it anywhere.

please do

window.onload = addList();

or trigger it on some other event

after its definition

see this fiddle

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.