ASP Net Center.com

 
JavaScript
Introduction
Variables & Arrays
Functions
If Statements
Case Statements
Loop Statements
Alert
Form Processing
Date Objects
Window Objects

Javascript Case Statements

Javascript case statements can be used to control the different outcomes of a condition. Javascript case statements are recommended when a single condition has a range of outcomes. For example, getDate is a method that can return any day of the week. Javascript case statements can be used to determine and display a message related to the current day.
 
The syntax for javascript case statements are as follows:
switch(condition)
{
case value:
action statement
}
The case value is executed when the condition is "true". If no match is found, then the default condition is executed (if specified).
 
This example uses a javascript case statement to display the current day:
 
<html>
<body>
<script type="text/javascript">
<!--
var date = newDate()
today = date.getDay()
switch (today)
{
case 1:
  alert("It's Monday")
  break
case 2:
  alert("It's Tuesday")
  break
case 3:
  alert("It's Wednesday")
  break
case 4:
  alert("It's Thursday")
  break
case 5:
  alert("It's Friday")
  break
case 6:
  alert("It's Saturday")
  break
case 7:
  alert("It's Sunday")
  break
}
//-->
</script>
</body>
</html>
Here we declared a variable 'date', and set it to the date object.
 
getDay accesses the days of the week in numbers 1-7.
switch sets the condition to test.
case tests the value, and executes when it's "true".
break is used to "break" the condition.
 
Since the condition is always "true" (hence everyday is a day), there is no need to specify a default statement to execute when there is no match. The example executes when the page is loaded since it's located in the 'body' section of the document.
 
This next example requests the user to enter a number between 1 and 3. If the wrong number is entered, the default value is executed.
<body>
<script type="text/javascript">
var number = prompt("Enter a number between 1 to 3:", 0)
switch (number)
{
case (number = "1"):
  alert("You typed" + number);
break
case (number = "2"):
  alert("You typed " + number);
break
case (number = "3"):
  alert("You typed " + number);
break
default:
  alert("Sorry, wrong number");
break
}
</script>
</body>

If Statements Loop Statements