Switch Statement
A switch statement can be thought of as an if else statement. They work very similar in that
they check to see if a condition is met, and if so then some code is executed. Here is an
example of a switch statement.
switch(n){
case 1:
do something
break
case 2:
do something else
break
}
In this switch statement, if case one is true then the script does something. If case 2 conditions are true then the script excutes to do something else. Below is a script that allows the user to input their favorite color, and then the script will display a message about that color.
<script language="JavaScript" type="text/javascript">
function favColor(color){
color = color.toLowerCase()
switch(color){
case "blue":
document.getElementById("fav_color").innerHTML = "The oceans are " + color
break
case "red":
document.getElementById("fav_color").innerHTML = "Red is the color of love."
break
case "yellow":
document.getElementById("fav_color").innerHTML = "Yellow reminds me of the sun."
break
case "green":
document.getElementById("fav_color").innerHTML = "And the green grass grows all around, and the green grass grow all around."
break
case "orange":
document.getElementById("fav_color").innerHTML = "I like the fruit just as well"
break
default:
document.getElementById("fav_color").innerHTML = "I am for sure " + color + " is a great color."
}
}
</script>
<body>
<form name="input">
<input type="text" name="color">
</form>
<button onclick="favColor(document.input.color.value)">Send</button>
<br>
<span id="fav_color"></span>
Something that this script does not have that the first switch statement does is the default switch. If you have a default switch in the switch statement, this will allow some code to be executed if none of the cases are true. In this script we have five cases, and there is a very large possibility that someone's favorite color is not one of those. To still give this user a message, the default switch will be ran and the user will still get a message. Below is an example of the switch statement in action.
iEntry 10th Anniversary
CSS Snippets
JavaScript Snippets