The Power of Javascript: Controlling the Execution of the Script - The switch example
(Page 6 of 6 )
Copy (or write) the following code into an HTML document and load it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World</title>
<script language="JavaScript" type="text/javascript">
var someText;
someText = prompt("Please enter some text", "I like Javascript");
switch(someText)
{
case "I like Javascript":
alert("You have written, " + someText);
break;
case "I like scritping languages":
alert("You have written, " + someText);
break;
case "I like Perl":
alert("You have written, " + someText);
break;
default:
alert("You have written, " + someText);
break;
}
document.write("<h3>This is the first statement after the switch statement</h3>");
</script>
</head>
<body>
</body>
</html>
Enter the value "I like Perl" into the prompt box.

A message box is displayed telling you what you have written.

And the following line is written to the Web page.

In our script we have a switch statement which tests the variable someText for the possible values that we enter. When you entered the string value "I like Perl" the interpreter assigned this value to the variable someText, then in the switch statement it goes through the case sections one by one until a match is found in the third case section. The Interpreter then executes this case's statements which display the message box. Let's do something else with this example. Remove the default section from the switch statement so it will look like this:
switch(someText)
{
case "I like Javascript":
alert("You have written, " + someText);
break;
case "I like scritping languages":
alert("You have written, " + someText);
break;
case "I like Perl":
alert("You have written, " + someText);
break;
}
Now save and reload the document and type the string value "hi" into the prompt's text box, then click OK. As you can see there's no message box telling you about the value you have written because we removed the default section. The interpreter goes through the case sections, but does not find any match, so it terminates the switch block and starts at the following statement in the script.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |