You are here: irt.org | FAQ | JavaScript | Form | Q1694 [ previous next ]
It's been known for some time that you could affect the items in one select box from the choice selected in another select box by using frames. This seemed messy and a lot of extra work to me, so I came up with this method to do it client-side without the need for hidden frames or additional server requests. I have not verified it on all browser versions, but it does work on IE5 and NS4.7
<script language="JavaScript"><!-- function UpdateList(object) { // Remove all existing items from select2 list object.select2.options.length = 0; var defaultSelected = false; var selected = false; // add items based on the selected option of select1 if (object.select1.options[object.select1.selectedIndex].value == "default") { var optionName = new Option("Default", "default", defaultSelected, selected); var length = object.select2.length; object.select2.options[length] = optionName; } if (object.select1.options[object.select1.selectedIndex].value == "FirstOption") { var optionName = new Option("ItemOneText", "ItemOneValue", defaultSelected, selected); var length = object.select2.length; object.select2.options[length] = optionName; var optionName = new Option("ItemTwoText", "ItemTwoValue", defaultSelected, selected); var length = object.select2.length; object.select2.options[length] = optionName; } if (object.select1.options[object.select1.selectedIndex].value == "SecondOption") { var optionName = new Option("FirstItemText", "FirstItemValue", defaultSelected, selected); var length = object.select2.length; object.select2.options[length] = optionName; var optionName = new Option("SecondItemText", "SecondItemValue", defaultSelected, selected); var length = object.select2.length; object.select2.options[length] = optionName; } // Do the next line to make sure the top item is selected object.select2.options[0].selected = true; } //--></script> <form name="formname"> <select name="select1" size="1" onChange="UpdateList(document.formname);"> <option value="default">Default</option> <option value="FirstOption">First Option</option> <option value="SecondOption">Second Option</option> </select> <select name="select2" size="1"> <option value="default">default</option> </select> </form>
Submitted by Shawn Clabough