How to create dynamic select boxes?
The example shows how to create two select boxes where a second listbox's selections are dependant on the item selected in the first listbox.
<html>
<head>
<script language="javascript">
function setOptions(o)
{
var select2 = document.form1.select2;
select2.options.length = 0;
if (o == "1")
{
select2.options[select2.options.length] = new Option('Apple');
select2.options[select2.options.length] = new Option('Pear');
}
if (o == "2")
{
select2.options[select2.options.length] = new Option('Carrot');
select2.options[select2.options.length] = new Option('Potatoe');
}
if (o == "3")
{
select2.options[select2.options.length] = new Option('Chicken');
select2.options[select2.options.length] = new Option('Fish');
}
}
</script>
</head>
<body>
<form name="form1">
<select name="select1" size="1" onchange="setOptions(document.form1.select1.options[document.form1.select1.selectedIndex].value);">
<option value="1">Fruit</option>
<option value="2">Vegetable</option>
<option value="3">Meat</option>
</select>
<br />
<br />
<select name="select2" size="1">
<option>Apple</option>
<option>Pear</option>
</select>
</form>
</body>
</html>
Display one set of the options (eg. Fruit - Apple, Pear) in HTML so that it will always be displayed when the page is loaded.
var select2 = document.form1.select2;
This creates a reference to the second listbox where the dynamically selected options will appear.
select2.options.length = 0;
This sets the second listbox options length to zero. It is very important to do this, or it will grow endlessly.
(document.form1.select1.option[document.form1.select1.selectedIndex].value);
This gets the selected value of the first listbox and passes it to the conditional statement.
if (o == "1")
If the selected value of the first listbox equals the value in the condition,
the options defined in the Option array will appear in the second listbox.
Related threads:
<select> question
JavaScript FAQ