This html attaches the function setOption
to the onchange
-event. According to quirksmode the change event is buggy. So you might have to fix / expand to improve cross browser compatibility.
<select id="s1" onchange="setOptions()">
<option>Pizza</option>
<option>Pasta</option>
<option>HotDogs</option>
</select>
<select id="s2">
<option>Pizza 1</option>
<option>Pizza 2</option>
<option>Pizza 3</option>
</select>
This javascript changes the options of the second select s2
after the selected option of the first select s1
was changed - the onchange-event was fired:
function setOptions()
{
document.getElementById('s2').options.length = 0; // remove all options
var selIndex = document.getElementById("s1").selectedIndex;
if(selIndex == 0)
addAllOptions('s2', ["Pizza Diavolo","Pizza Veggie"]);
else if(selIndex == 1){
addAllOptions('s2', ["Pasta Napoli","Pasta Primavera"]);
}
else{
addAllOptions('s2', ["Hot Dog Chilie King","Hot Dog Silent Wiener"]);
}
}
And to add options
function addAllOptions(selectID, values)
{
var arrayLength = values.length;
for (var i = 0; i < arrayLength; i++) {
appendOptionLast(selectID,values[i]);
}
}
This function might need be be enhanced as well to improve cross browser compabillity.
// see http://www.mredkj.com/tutorials/tutorial005.html
function appendOptionLast(selectID, num)
{
var elSel = document.getElementById(selectID);
var elOptNew = document.createElement('option');
elOptNew.text = num;
elOptNew.value = 'a_' + num;
try {
elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
}
catch(ex) {
elSel.add(elOptNew); // IE only
}
}
See the fully working demo
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…