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. As you can see in Figure 2.13, this script returns one of three different Presidential quotes as alert dialogs, depending on which button the user clicks. Script 2.14 shows the HTML, which is fairly simple. Script 2.15, the JavaScript, uses the switch/case construct to differentiate between presidents.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Switch/Case handling</title> <script type="text/javascript" src="script09.js"></script> </head> <body bgcolor="#FFFFFF"> <h2>Famous Presidential Quotes</h2> <form action="#"> <input type="button" id="Lincoln" value="Lincoln" /> <input type="button" id="Kennedy" value="Kennedy" /> <input type="button" id="Nixon" value="Nixon" /> </form> </body> </html> |
To use a switch/case statement:
✓ Tip
A switch statement can be passed other values besides strings. You can use it with a numeric value or even have it evaluate a mathematical result. If its result should be numeric, though, be sure that the case statements match—your case statements would then need to check for numbers, not strings (e.g., 5, not “5”).
3.145.166.167