Reputation: 974
Ok, I know how to do this - in theory. I have a dropdown list in a web page that I want to edit dynamically with javascript. My dropdown list has been created, empty, with the following HTML:
<select id="my_dropdown">
</select>
and then this javascript code (run in the head section) is supposed to fill it in with a single option:
my_drop = document.getElementById("my_dropdown");
my_drop.options[0] = new Option("Name", "value");
I think I'm doing everything by the books but, even stripped to the bone at this point, this code still doesn't work, either on Chromium or Firefox. I have no idea what to try next. Suggestions?
Upvotes: 0
Views: 299
Reputation: 36531
nothing is wrong with your code... i think your DOM isn't ready so try this...
on your HTML tag
<body onload="myFunction()">
and add this to your script
function myFunction(){
my_drop = document.getElementById("my_dropdown");
my_drop.options[0] = new Option("Name", "value");
}
Upvotes: 0
Reputation: 136114
If you're doing it in the head, ouside of any onload
handler, then the DOM is not ready yet.
Either move your javascript to after the element in the HTML, or enclose it in an onload
function.
eg/
<body onload="doMyStuff()">
and in the head
function doMyStuff(){
// code here to add item to dropdown
}
Upvotes: 1