[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
How_To_Javascritp_Create_Dynamic_Select_Boxes
Display one set of the options (eg. Fruit - Apple, Pear) in HTML so that it will always be displayed when the page is loaded.
This creates a reference to the second listbox where the dynamically selected options will appear.
This sets the second listbox options length to zero. It is very important to do this, or it will grow endlessly.
This gets the selected value of the first listbox and passes it to the conditional statement.
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
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
How_To_Javascritp_Create_Dynamic_Select_Boxes
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
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
