One of
my best and most complicated JavaScript trick is changing a second
drop down list based on the selected value of the first drop down
list. This is frequently required in a web application. For example,
I work on a web site that sells auto parts and they need the vehicle
models drop down list to change based on the vehicle make selected.
This gets particularly challenging if the drop down lists are
populated from a database because then you need to mix code in two
languages; client side JavaScript and server side VBScript.
Since
this is client side JavaScript, the demo works on this page.
Changing Select Options
<script type="text/javascript">
<!--
function changeOptions() {
if (document.getElementById("genre").options[document.getElementById("genre").selectedIndex].value == "Science Fiction") {
with (document.getElementById("authors")) {
for (i = options.length - 1; i > 0; i--)
options[i] = null;
options[0] = new Option("Isaac Asimov");
options[0].value = "Isaac Asimov";
options[1] = new Option("Arthur C Clarke");
options[1].value = "Arthur C Clarke";
options[2] = new Option("Ben Bova");
options[2].value = "Ben Bova";
options[0].selected = true;
}
}
if (document.getElementById("genre").options[document.getElementById("genre").selectedIndex].value == "Drama") {
with (document.getElementById("authors")) {
for (i = options.length - 1; i > 0; i--)
options[i] = null;
options[0] = new Option("Eugene O'Neill");
options[0].value = "Eugene O'Neill";
options[1] = new Option("William Shakespeare");
options[1].value = "William Shakespeare";
options[2] = new Option("Samuel Beckett");
options[2].value = "Samuel Beckett";
options[0].selected = true;
}
}
if (document.getElementById("genre").options[document.getElementById("genre").selectedIndex].value == "Poetry") {
with (document.getElementById("authors")) {
for (i = options.length - 1; i > 0; i--)
options[i] = null;
options[0] = new Option("Arthur Rimbaud");
options[0].value = "Arthur Rimbaud";
options[1] = new Option("Sylvia Plath");
options[1].value = "Sylvia Plath";
options[2] = new Option("Charles Bukowski");
options[2].value = "Charles Bukowski";
options[0].selected = true;
}
}
}
//-->
</script>
<select id="genre" name="genre" size="1" onChange="changeOptions()">
The select that triggers the change.
Using getElementById("") works in
most browsers.
Internet Explorer considers
"author" to be a reserved word. I had to change my id to
"authors".
Example
|