Reputation: 2578
I need one <select>
dropdown to change based on another. Here is what I have so far, which is not working.
HTML
<html>
<head>
...
</head>
<body>
<form>
<table>
<tr>
<td>Dropdown Menu 1</td>
<td>Dropdown Menu 2</td>
</tr>
<tr>
<td>
<select id="ddl1" onchange="changeDropdown(this,document.getElementById('ddl2'))">
<option value=""><!---------></option>
<option value="Colors">Colors</option>
<option value="Shapes">Shapes</option>
<option value="Sounds">Sounds</option>
</select>
</td>
<td>
<select id="ddl2">
</select>
</td>
</tr>
</table>
</form>
</body>
</html>
Javascript
<script>
function changeDropdown(ddl1,ddl2) {
var colors = new Array('Black', 'Brown', 'Blue');
var shapes = new Array('Triangle', 'Square', 'Circle');
var sounds = new Array('Loud', 'Soft');
switch (ddl1.value) {
case 'Colors':
for (i = 0; i < colors.length; i++) {
createOptions(ddl2, colors[i], colors[i]);
}
break;
default:
ddl2.options.length = 0;
break;
}
}
function createOptions(ddl,text,value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.option.add(opt);
}
</script>
This needs to be in Javascript. I know that people usually advice jQuery for stuff like this, but this needs to be Javascript.
What am I doing wrong?
Thanks in advance!
-Anthony
Upvotes: 0
Views: 1198
Reputation: 3940
Instead of:
opt.option.add(opt);
Do:
ddl.appendChild(opt);
Upvotes: 1
Reputation: 781
This works:
function createOptions(ddl,text,value) {
var opt = document.createElement('option');
opt.setAttribute("value", value);
opt.innerHTML=text;
ddl.appendChild(opt);
}
Upvotes: 1