Add Item To Dropdown List in HTML Using Javascript: Sign Up Log in Tour Help
Add Item To Dropdown List in HTML Using Javascript: Sign Up Log in Tour Help
Add Item To Dropdown List in HTML Using Javascript: Sign Up Log in Tour Help
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up ×
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>
</body>
</html>
javascript html
possible duplicate of how do I add an option to a html form dropdown list with javascript – Hashem Qolami
Aug 24 '13 at 9: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 9:48
5 Answers
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);
}
};
<body onload="addList()">
http://stackoverflow.com/questions/18417114/add-item-to-dropdown-list-in-html-using-j... 04/01/2016
add item to dropdown list in html using javascript - Stack Overflow Página 2 de 3
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.
function escapeHTML(str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
i think you have only defined the function. you are not triggering it anywhere.
please do
window.onload = addList();
Try this:
select.appendChild
(option);
Try this
http://stackoverflow.com/questions/18417114/add-item-to-dropdown-list-in-html-using-j... 04/01/2016
add item to dropdown list in html using javascript - Stack Overflow Página 3 de 3
<script type="text/javascript">
function AddItem()
{
// Create an Option object
var opt = document.createElement("option");
http://stackoverflow.com/questions/18417114/add-item-to-dropdown-list-in-html-using-j... 04/01/2016