I\'m trying to build a two tier drop down menu where the second drop down populates the second. I\'ve found a lot of examples on the site but I want my menu to redirect to
I want the page to redirect to somewhere on the site after the person makes a selection in the second drop down.
Hook on the change
event of the second <select>
element, and then submit the form from there:
<select id="ddl2" onChange="redirect(this)">
</select>
function redirect(select) {
// The simplest way: call submit on the form element the select belongs to:
select.form.submit();
}
But you could also change the target attribute of the form dynamically before submitting, or just navigate away.
Update: To make the submit work, you of course would need to give your selects some name
attributes, like:
<form action="/router.php" method="GET">
<select name="first" onchange="configureDropDownLists(this,'ddl2')">
...
</select>
<select name="second" id="ddl2" onChange="redirect(this)">
</select>
</form>
Although your configureDropDownLists
function may work, you might improve it by not using a switch statement, but an object literal, and just select the array of option values before executing the same thing if one was found in the object:
function configureDropDownLists(firstSelect, secondId) {
var map = {
"colours": ['Black', 'White', 'Blue'],
"shapes": ['Square', 'Circle', 'Triangle'],
"names": ['John', 'David', 'Sarah']
};
var value = firstSelect.value.toLowerCase();
var optionsArr = map[value];
var secondSelect = document.getElementById(secondId);
secondSelect.options.length = 0; // remove all options
if (optionsArr) {
for (var i=0; i<optionsArr.length; i++) {
createOption(secondSelect, optionsArr[i], optionsArr[i]);
}
}
}