HTML Goodies: Script Tip: Week 40
Script Tip life begins at 40...
Okay! We now know how to get a drop-down menu to react using a button to fire up the function. But what if you don't like the button? Wouldn't it be better to just let the user choose their selection and off they go... sans button? It looks like this:
The code looks like this:
var number = document.DropDown.DDlinks.selectedIndex;
location.href = document.DropDown.DDlinks.options[number].value;
<SELECT NAME="DDlinks" onChange="LinkUp(this.form)" >
<OPTION SELECTED>Choose a Link
<OPTION VALUE="scripttip1.html"> Page One
<OPTION VALUE="scripttip2.html"> Page Two
<OPTION VALUE="scripttip3.html"> Page Three
This is a rather easy effect to generate. Notice that the button code has been taken out. The function remains the same, as does the code for the drop- down box itself. Here's the new code that does the trick:
<SELECT NAME="DDlinks" onChange="LinkUp(this.form)">
An Event Handler, onChange, is used to fire the function, LinkUp(). onChange works just as you think it does. As soon as something changes, it's triggered. When the page loads, the OPTION SELECTED is the item displayed. Once someone changes that, the function is triggered.
This hasn't come up a lot in the Script Tips, but do you see the text within the instance (the parentheses)? That text is known as a "parameter." In this case, it is information that is going to be passed to the function.
The information passed to the function couldn't be more clear, this.form. The output of the form, the index number of the user's choice, is sent up to the function and used, along with the VALUE, to create the hypertext link just as it was when we had the button.
One more thing -- notice where I placed the onChange Event Handler. It is in the SELECT flag, not the first OPTION flag. That's because the SELECT will change. The first OPTION will always stay the same and never trigger the function.
Easy enough... but will it work across frames?! Sure.
Next Week: Across Frames