Categories:

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:

Example:

Source code:

<form name="classic">
<select name="countries" size="4" onChange="updatecities(this.selectedIndex)" style="width: 150px">
<option selected>Select A City</option>
<option value="usa">USA</option>
<option value="canada">Canada</option>
<option value="uk">United Kingdom</option>
</select>

<select name="cities" size="4" style="width: 150px" onClick="alert(this.options[this.options.selectedIndex].value)">
</select>
</form>

<script type="text/javascript">

var countrieslist=document.classic.countries
var citieslist=document.classic.cities

var cities=new Array()
cities[0]=""
cities[1]=["New York|newyorkvalue", "Los Angeles|loangelesvalue", "Chicago|chicagovalue", "Houston|houstonvalue", "Austin|austinvalue"]
cities[2]=["Vancouver|vancouvervalue", "Tonronto|torontovalue", "Montreal|montrealvalue", "Calgary|calgaryvalue"]
cities[3]=["London|londonvalue", "Glasgow|glasgowsvalue", "Manchester|manchestervalue", "Edinburgh|edinburghvalue", "Birmingham|birminghamvalue"]

function updatecities(selectedcitygroup){
	citieslist.options.length=0
	if (selectedcitygroup>0){
		for (i=0; i<cities[selectedcitygroup].length; i++)
			citieslist.options[citieslist.options.length]=new Option(cities[selectedcitygroup][i].split("|")[0], cities[selectedcitygroup][i].split("|")[1])
	}
}

</script>

I used a separate array ("cities[0]", "cities[1]" 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 any way. 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() constructor.

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 admission?