29

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> 
Syscall
  • 19,327
  • 10
  • 37
  • 52
  • possible duplicate of [how do I add an option to a html form dropdown list with javascript](http://stackoverflow.com/questions/10992261/how-do-i-add-an-option-to-a-html-form-dropdown-list-with-javascript) – Hashem Qolami Aug 24 '13 at 09:40
  • @HashemQolami I do not have a button and hence I am confused on where to put the function. – Oyindamola 'Funmi Oni Aug 24 '13 at 09:48

5 Answers5

31

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()">
Kabie
  • 10,489
  • 1
  • 38
  • 45
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);
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
  • How about if I just want to replace the value instead of appending? How would I do that? – Eli Sep 29 '16 at 12:05
1

Try to use appendChild method:

select.appendChild(option);
Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
Alex
  • 12,205
  • 7
  • 42
  • 52
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.

Golda
  • 3,823
  • 10
  • 34
  • 67
  • 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); } – Bbb May 25 '18 at 16:34
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

Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101