Linked Dropdowns

Do you have multiple dropdown lists in one of your forms? Is the value that is selected in one dropdown dependent on the value selected in a second dropdown?

A simple JavaScript function can link two drop down lists together so that selecting a particular value in one list will automatically select the same value in a second list.

Here's an example. You can select whatever entry you like in the "Real" dropdown and it will have no effect on the "Estimate" dropdown. That's what you would expect anyway. If you select any of the options in the "Estimate" dropdown other than the blank entry at the top the "Real" dropdown entry will be automatically changed to the same entry.

Real: Estimate:

The first thing you need to do to link two dropdowns together like this is to write the HTML for the dropdown lists. Here is the code that I used for the example (note the code in bold which is needed to link in the JavaScript.

<form action="#">
Real: <select id="actual">
<option value=" " selected="selected"></option>
<option value="A">Option One</option>
<option value="B">Option Two</option>
<option value="C">Option Three</option>
<option value="D">Option Four</option>
</select>
 
Estimate: <select onchange="listSel(this,'actual')">
<option value=" " selected="selected"></option>
<option value="A">Option One</option>
<option value="B">Option Two</option>
<option value="C">Option Three</option>
<option value="D">Option Four</option>
</select>
</form>

The JavaScript code to link these two together is fairly straightforward as well.

function listSel(fld,id) {
var opt = fld.selectedIndex;
if (fld[opt].value != ' ') {
var sel = document.getElementById(id);
for (var i = sel.options.length -1; i > -1; i--) {
if (fld[opt].value == sel[i].value) sel[i].selected = true;
}
}
}

To apply that exact link between two of your dropdowns simply save the JavaScript as shown to a file (eg. droplist.js) and then link it into the head of your web page like this:

<script type="text/javascript" src="droplist.js">
</script>

If you don't want to exclude blank values from the link then remove the first if statement line along with the corresponding end } on the second last line. If instead you want to exclude additional values from the link simply modify that if statement to test for all of the values to be excluded. Any values that exist in the second list and not in the first will be automatically excluded (for obvious reasons) without your needing to add code for them.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate