Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add item to dropdown list in HTML using JavaScript

Tags:

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>  
like image 607
Oyindamola 'Funmi Oni Avatar asked Aug 24 '13 09:08

Oyindamola 'Funmi Oni


1 Answers

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()"> 
like image 130
Kabie Avatar answered Oct 29 '22 14:10

Kabie