Knowledge Base Articles » KB100209: Dynamically altering the contents of an HTML Select List.

This article explains how to alter the contents of one HTML Select list, based on the selection made in a second HTML Select list.

The example below demonstrates this by updating the contents of a City Select list, to contain only cities that are in the state currently selected in the State Select list.

 
States:
Cities:


Since all of this processing is done on the client side (in the browser), the HTML document sent to the browser must store all the possible cities for all the possible states. This can be achieved by using JavaScript to place them in an array of arrays as illustrated by the following code. Note that JavaScript does not natively support multi-dimensional arrays (but you can emulate such arrays).

<script type="text/javascript">
// Create arrays containing state cities
// Note: These arrays could be created dynamically
var arrStates, arrFlorida, arrNewYork, arrTennessee
arrFlorida = ["Daytona Beach", "Miami", "Orlando", "Tampa"]
arrNewYork = ["Albany","New York", "Oakland", "Rochester"]
arrTennessee = ["Gatlinburg", "Knoxville", "Memphis", "Nashville"]
arrStates =[arrFlorida, arrNewYork, arrTennessee]


We then simply specify an onchange event-handling function for the master Select list (in this case, State) which dynamically replaces the contents of the dependent select list (in this case, City) with the options defined in the appropriate array.

Using this technique does avoid having to make a round-trip to the server every time a new option is selected in the master list. However, download times can be slow as your page must now contain an array of arrays that list every possible value for both Select lists.

To view the source code for the above example, click the link below.

View source for select example