A few examples cover client side approaches to this problem, and this article will cover how to use Javascript on the client side to populate the values of another dropdown depending on the selected value in a dropdown.
For this example, we shall use the following simple HTML file which contains one Form and two dropdowns. The following table of data shows the values that should be displayed in teh second dropdown depending on the value selected in the first for this example :
First Dropdown | Second Dropdown |
---|---|
A | 1 |
A | 2 |
A | 3 |
B | 4 |
B | 5 |
C | 6 |
From this we can see that if we select A in the first dropdown, then our options in the second dropdown should be 1, 2 or 3.
To provide the functionality that we need we first need to amend the code of the first dropdown, we need to add an action so that when a value is selected our code is run to set the values in the second dropdown, in this case we shall get it to call a Javascript function - which we will create later - called populateDD.
<SELECT NAME="first_dropdown" ONCHANGE="populateDD();">
We can now focus on the Javascript function itself. To achieve the desired result, our function needs to perform several distinct tasks, which can be defined as follows :
- Remove all elements from the second dropdown.
- Get the value selected in the first dropdown.
- Get the values that should be put in the second dropdown depending on the value of the first dropdown.
- Populate the second dropdown.
To assist with the population of the second dropdown, I have decided to write a seperate function that I can use to populate this dropdown. This function has been written in a generic manner, which means that I can use it to update any dropdown on any form. The code for this generic function is as follows :
// function takes a display NAME and the VALUE for the new element and then adds it to the dropdown specified in the other parameter
function addOption(whichDD,name,value)
{
// create a reference to the SELECT and the form
var theDD=eval(whichDD);
// create the new OPTION
var newOption;
newOption= new Option (name,value);
// position
var insertAt = theDD.options.length;
// create the space
theDD.options.length=theDD.options.length + 1;
// add the option
theDD.options[insertAt] = newOption;
}
function populateDD()
{
// get the value
var firstDD=document.myForm.first_dropdown.value;
// reset the dropdown
document.myForm.second_dropdown.length=0;
// Populate the second DD
switch (firstDD)
{
case 'A':
addOption('document.myForm.second_dropdown','1','1');
addOption('document.myForm.second_dropdown','2','2');
addOption('document.myForm.second_dropdown','3','3');
break;
case 'B':
addOption('document.myForm.second_dropdown','4','4');
addOption('document.myForm.second_dropdown','5','5');
break;
case 'C':
addOption('document.myForm.second_dropdown','6','6');
break;
}
}