|Play with this example by selecting the different animals (dogs, fish,
My favorite animal is ...
To start off with look at the form itself.
The <FORM> has two <SELECT> Objects. The first pulldown has an onChange Handler that calls a function called swapOpts(). swapOpts() has one parameter -- the selected animal type.
The defined Arrays are:
Notice that the Arrays are named the same thing as the animals in the first pulldown.
Now look at the function that gets called when the first pulldown is changed:
The function definition includes one parameter: ArrayName. If you chose "fish," the ArrayName will equal the string "fish."
The first line in the body of the function sets a variable to refer to the second form element, the second <SELECT> Object.
The end result of the second line is that the variable theArray will equal one of the Arrays defined above. If the ArrayName is "Fish," theArray will equal the Fish Array.
NOTE: eval(ArrayName) in this case transforms a String "fish" into an Array Object called "fish". eval() always transforms a String into something else. In Week 3 we saw how eval() changed Strings into Image Objects and also variables.
The third line of the function calls another function called setOptionText(). setOptionText() does the work of setting the values of the second pulldown to the contents of theArray. Here it is:
This function takes two parameters, a reference to a <SELECT> Object and an Array. The first line of the function sets up a for loop, which loops through all the options in the <SELECT> Object. NOTE: the options property of a <SELECT> is an Array of all that Select's Options. Because it is an Array you can find out how many options are in a <SELECT> using the length Property of Arrays.
The first time you hit the loop, the loop variable equals 0. The body of the loop then reads:
If you chose "Fish" in the pulldown, theArray will be "trout," so this line will change the first <OPTION> in the list select to "trout." The next time through the loop, loop will equal 1, and the second <OPTION> in the list will equal "mackerel."