Creating a 2 level interdependent select list
It may seem like a daunting task, but we actually know more
than enough now to create an interdependent select list, where selecting the
options of one select element changes the options of another with
corresponding content. Lets see the full code first:
<select name="countries" size="4"
onChange="updatecities(this.selectedIndex)" style="width: 150px">
<option selected>Select A City</option>
<option value="uk">United Kingdom</option>
<select name="cities" size="4" style="width: 150px"
var cities=new Array()
cities=["New York|newyorkvalue", "Los Angeles|loangelesvalue",
"Chicago|chicagovalue", "Houston|houstonvalue", "Austin|austinvalue"]
for (i=0; i<cities[selectedcitygroup].length; i++)
I used a separate array ("cities", "cities" etc) for
each city group, with each array element containing the name/value pair of a
city (separated by "|"), The separator makes it easy to separate the name
and value pair when called for. Function updatecities() is where all the
magic occurs, which fortunately isn't magical in anyway. Here's a quick
rundown of what it does:
Firstly, it empties the "cities" select list each time
it's run, by setting citieslist.options.length=0
Then, using a for loop, it loops through array
cities[selectedcitygroup], where "selectedcitygroup" contains the index of
the "countries" list option that's currently selected (which also corresponds to
the index of array cities that contains the cities for that country).
For each iteration, a new option is added to the "cities"
select list, using the split() function to first divide the name/value
pair of each city and entering them as parameters into the Option()
And that's all there is to it! With the basic techniques
down, you can easily create interdependent select lists, or single select
lists that dynamically change content. Now isn't that worth the price of