One question that frequently appears in help forums has to do with linking multiple select lists on a web form, for example, when a user selects a particular state, the select list comprising cities would only display the relevant values for that particular state. In another article, I show how one can submit the form to itself and use the request object as a parameter to create server-side SQL selects.
For this discussion, we will take as the example car makes and models, the goal being that a selection from manufacturers drop down will populate the model select list with the corresponding models. See the code in action here.
I start by creating an array called arrModels. The tricky bit is that I immediately assign the value of a new array to each of the array elements. Next, I populate each of these arrays with values that I will need for my select lists: an empty value for the default selection--arrModels; the Tempo, Taurus, and Windstar for the Ford selection--arrModels; and the Tercel, Corolla, Camry, and Avalon for the Toyota selection arrModels.
As will become clear later in the code, we can use the selected index from the manufacturer select list to point to the related associative array, and then iterate through that array to populate the models select control.
This approach, however, suffers from a deficiency. It will work fine if I don't want to specify a value attribute for the select control or if I want to have the same text for both the display and value attributes. If I want to have separate text for the value and for the display, then I need to modify my array structures somewhat. Example 2 shows the necessary modification:
While this structure is somewhat more complex, it will allow us to specify a separate item for the value and the display text.
The next step is to create the code that uses the selected index from the manufacturers select list to populate the models select list. The code is in example 3.
The first couple of lines declare some variables and set the values from the form elements to them. The next two lines reset the models select list to remove any existing elements and to set the selected index to 0. With that out of the way, we can use the new Option() method to dynamically create options for our models select object and use the .value and .text properties to populate them with the values from the arrays. The naming convention in the associate arrays allows a simple counter to iterate through and grab the values. The final line sets the focus to the models control.
Even though I have set this example for two select lists, it could easily be expanded to three or more lists. By passing two para maters to the FillList() function--the name of the two select lists--you could generalize and expand this approach.
The source for the whole page is available here.(Return to Main Code Corner Page)
If you found this article helpful and you would like to make a donation, please click on the PayPal button below.