- Detecting Browser Plug-ins
- Around and Around with Loops
- Writing with Loops
- Using For/In Loops
- Using Do/While Loops
- Checking if Java Is Enabled
- Functions
- Using Multi-level Conditionals
- Working with Functions That Return Values
- Handling Errors
- Putting More than One Script on a Page
- Scrolling Status Bars
- Status Bar Messages
Using Multi-level Conditionals
There are times when you need more than two choices in a conditional test; then and else sometimes just aren't enough. While you can have nested levels of if, it's often simpler to just use a switch/case statement instead. The switch/case construct allows you to check a variable against multiple values. Script 3.8 , based on Script 3.7, uses the switch/case construct to differentiate between presidents.

Script 3.8 This type of conditional allows you to check against multiple possibilities.
To use a switch/case statement
- function saySomething(buttonName) { Whereas in Script 3.7 we passed in the text that we wanted to display, in this script we're only passing in the name of the button itself.
- switch(buttonName.value) { The value of buttonName is used as the parameter to switch(). Its value will decide which of the below case statements will get executed.
-
case "Lincoln": alert("Four score and seven years
If its value is "Lincoln," this alert will appear. Figure 3.12 shows that the result of this script looks pretty much like the previous one.ago...")
Figure 3.12 Although the code may be different, the result is the same.
- break If the user clicked on "Lincoln," you're in this section of code. However, you've done everything you want to do, and so you want to get out of the switch. In order to do that, you need to break out. Otherwise, you'll execute all of the code below, too. While that continued execution can be handy in certain circumstances, this isn't one of them.
-
case "Kennedy": alert("Ask not what your country
If the user clicked on "Kennedy," we end up in this case block.can do for you...") break
-
case "Nixon": alert("I am not a crook!") break
And finally, if the user clicked on "Nixon," we end up here, popping up another alert and then breaking out of the switch. - default: If you were wondering what would happen if the user's entry didn't meet one of the above criteria, you're in the right place. The default section is where you end up if your switch value didn't match any of the case values. The default block is optional, but it's always good coding practice to include it, just in case (so to speak). In this script, there's no code here to execute, because we shouldn't ever get here.
- } This closing brace ends the switch statement.
-
<input type="button" value="Lincoln"
Unlike Script 3.7, all of the buttons in this script have identical onclick handlers. Using this (explained more in Chapter 8), allows all the real work to be done within the <script> area, so it impacts the HTML as little as possible.onclick="saySomething(this)" />