I need one <select>
dropdown to change based on another. Here is what I have so far, which is not working.
<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>
<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
This works:
function createOptions(ddl,text,value) {
var opt = document.createElement('option');
opt.setAttribute("value", value);
opt.innerHTML=text;
ddl.appendChild(opt);
}
Instead of:
opt.option.add(opt);
Do:
ddl.appendChild(opt);
opt.option.add(opt);
好像您要向自身添加选项。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.