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>
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()">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With