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 a page after the second menu is selected and can't figure that bit out.
I'm not that up to speed with JS so please bear with me.
The code below is an example from another post:
<script type="text/javascript">
function configureDropDownLists(ddl1,ddl2) {
var colours = new Array('Black', 'White', 'Blue');
var shapes = new Array('Square', 'Circle', 'Triangle');
var names = new Array('John', 'David', 'Sarah');
switch (ddl1.value) {
case 'Colours':
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < colours.length; i++) {
createOption(document.getElementById(ddl2), colours[i], colours[i]);
}
break;
case 'Shapes':
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < colours.length; i++) {
createOption(document.getElementById(ddl2), shapes[i], shapes[i]);
}
break;
case 'Names':
document.getElementById(ddl2).options.length = 0;
for (i = 0; i < colours.length; i++) {
createOption(document.getElementById(ddl2), names[i], names[i]);
}
break;
default:
document.getElementById(ddl2).options.length = 0;
break;
}
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
Then call it
<select id="ddl" onchange="configureDropDownLists(this,'ddl2')">
<option value=""></option>
<option value="Colours">Colours</option>
<option value="Shapes">Shapes</option>
<option value="Names">Names</option>
</select>
<select id="ddl2">
</select>
This all works fine, but I want the page to redirect to somewhere on the site after the person makes a selection in the second drop down.
Could anyone help with how to adapt the code to make that happen?
Thank you
Hook on the
change
event of the second<select>
element, and then submit the form from there: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: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: