1. Technology

Your suggestion is on its way!

An email with a link to:

http://javascript.about.com/library/bl3drop1.htm

was emailed to:

Thanks for sharing About.com with others!

Three Dynamic Dropdowns

The Javascript

Join the Discussion

Questions? Comments?

More of This Feature

Two Dropdowns Three Dropdowns

We have looked at the changes to the HTML that are needed to convert two linked dropdown lists into three linked dropdown lists. All that remains is to look at how we change the setOptions() function to handle the additional dropdowns.

The actual code within the function being called will be dependent on exactly how many options that you want to include in each list and what values and text that you want to give them. Here is the code from my sample version with the changed sections from the two dropdown version shown in bold. I have also left some sections out in order to reduce what I am showing here to a reasonable length but the removed sections are basically duplicates of those sections that immediately precede them.

function setOptions(chosen,selbox) {
// selbox assignment deleted
 
selbox.options.length = 0;
if (chosen == " ") {
  selbox.options[selbox.options.length] = new Option('Please select one of the options above first',' ');
setTimeout(setOptions(' ',document.myform.optthree),5);
 
}
if (chosen == "1") {
  selbox.options[selbox.options.length] = new
Option('first choice - option one','11');
  selbox.options[selbox.options.length] = new
Option('first choice - option two','12');
setTimeout(setOptions('11',document.myform.optthree),5);
}
// repeat for entries in first dropdown list

if (chosen == "11") {
  selbox.options[selbox.options.length] = new
Option('first choice - option one - sub one','111');
  selbox.options[selbox.options.length] = new
Option('first choice - option one - sub two','112');
}

// repeat for all the possible entries in second dropdown list
}

As you can see the basic change that we need is to add entries for all of the possible values passed from the second dropdown as well as the first (making sure that all of the values are unique). That is the obvious part of the update. The not so obvious part is that when an entry is selected in the first dropdown to setup the second dropdown the value in the second dropdown changes but the onchange event handler for that dropdown doesn't automatically get triggered. To resolve this we call the function that the event handler would normally trigger ourselves from within our code. This is actually calling the function that we are already running just passing it different parameters and so to make sure that we don't have any issues with browsers that have a dislike for recursive calls in Javascript we make the call using a setTimeout using a 5 microsecond delay in order to allow the current call to the function to complete first.

©2014 About.com. All rights reserved.