Dynamic Dropdown Boxes

Question: I'm wondering how to go about creating two dropdown boxes such that when you select a value from the first one, the second is populated with values that depend on the first.Michael Kennedy

Answer: Here is an example of a form where the content of the second dropdown box is dependent on what is selected in the first dropdown box and clicking on the button will display an alert showing the value associated with the selected entry in the second dropdown box. Note that while this works in Internet Explorer, Netscape (both 4 and 6+), and Opera 6+, it does not populate the second dropdown box in Opera 5 so you may want to advise your visitors of that. (Note that this version was written when IE5 was the latest version of IE, now that all the old browsers that were around when this was written are gone you can make the JavaScript far less obtrusive and keep it completely separate from the HTML).

The onchange function on the first dropdown box calls a javascript function called setOptions and passes it the value of the option selected in the first dropdown box. I've given the options values of 1, 2, and 3 but you can use whatever values you like and include as many options as you like.

The javascript function needs to be included in the head section of your page in order for it to work. Here is the example code:

All that you need to do to get this function to populate the second dropdown box with your desired values for each of the values in your first dropdown box is to repeat the if statement checking which entry was chosen for all of the different values that can be selected in your first dropdown box. Within each of these you have one selbox.options assignment statement for each value that you want to appear in the second dropdown box (I have included two options in each built you can have as many as you like). The first entry in the option field on the right is the literal that you want to appear as a selectable value in the dropdown box and the second entry is the value that you want to assign to the particular selection.

I have included a button at the end of the form that when clicked will display the value assigned by the second dropdown box just so you can see which value it is set to with the various combinations of selections in the two dropdown boxes. You don't need to include the button in your form but the code does show you how to test the value of the second dropdown box.

You can call your form whatever you want, just substitute its name wherever you see myform in the above example. Similarly you can change the names of the first and second dropdown boxes to whatever you like by substituting for optone and opttwo everywhere they appear.

Note: This page shows how this would have been done for early browsers such as Netscape 4. For a version better designed to work with modern browsers please see my revised cascading dropdown script.