Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Workshop: Evaluating a User Response

As a practical example of the switch statement, you can now create a Web page that asks the user a question, and then evaluates the user's response to determine what to do next. Specifically, you'll ask the user for a keyword that represents a Web page.

If the keyword matches one of those in your script, the user will be sent to the appropriate page. If the response doesn't match one of the predetermined keywords, the user will be sent to a default page.

Your script starts by prompting the user with the prompt function. To use this function, you include text that prompts the user as a parameter and assign the returned value to a variable. Here's the prompt statement:

where = prompt("Where do you want to go today?");

Next, use a switch statement and several case statements to evaluate the response:

switch (where) {
case "Netscape" :
        window.location="http://www.netscape.com/";
        break;
    case "Microsoft" :
        window.location="http://www.microsoft.com/";
        break;
case "Yahoo" :
        window.location="http://www.yahoo.com/";
        break;

Next, use the default statement to send the user to a default page (in this case, this book's site):

default :
        window.location="http://www.jsworkshop.com/";
}

Because this is the last statement in the switch structure, you don't need to use the break statement here. The final brace ends the switch statement.

Listing 6.1 shows the complete script embedded in a Web document. To test it, load the page. You should see a prompt, as shown in Figure 6.1. Next, enter one of the keywords. You should be sent to the appropriate page. If you specify an unknown keyword, you will be sent to the default page.

06fig01.jpg

Figure 6.1 Prompting for a user response.

Example 6.1. The complete user response example

<html>
<head><title>User Response Example</title>
</head>
<body>
<h1> User Response Example</h1>
Enter your destination.<br>
<script LANGUAGE="JavaScript1.2" type="text/javascript1.2">
where = prompt("Where do you want to go today?");
switch (where) {
case "Netscape" :
        window.location="http://www.netscape.com/";
        break;
    case "Microsoft" :
        window.location="http://www.microsoft.com/";
        break;
case "Yahoo" :
        window.location="http://www.yahoo.com/";
        break;
default :
        window.location="http://www.jsworkshop.com/";
}
</script>
</body>
</html>

Share ThisShare This

Informit Network