Ticker

6/recent/ticker-posts

JavaScript (Switch Statement)

SWITCH STATEMENT IN JAVASCRIPT

This statement is also used to implement two and more than two conditions, so its an alternative for else if statement.
The switch statement commonly use break keyword.
The break is used to exit from switch statement or from any other control statement such 


EXAMPLE 1: A simple example of switch statement

<html>
<title> Switch statement </title>
<body>
<form name="f">
Enter first number <input type="text" name="n1">
<br> <br>
Enter second number <input type="text" name="n2">
<br> <br>
1. Add 2. Sub
<br>
3. Mul 4. Div

<br> <br>
Enter your choice (1-4) <input type="text" name="ch">

<input type="button" value="Result" onclick="result()">
</form>

<script>
function result()
{
var a,b,c,r;
a=Number(f.n1.value)
b=Number(f.n2.value)
c= Number(f.ch.value)

switch(c)
{
case 1:
    r=a+b; break;

case 2:
    r=a-b; break;

case 3:
    r=a*b; break;

case 4:
    r=a/b; break;
default:
   alert("Wrong Choice");
}
alert("Result is;"+r);
}
</script>
</body>
</html>


EXAMPLE 2: Create a simple shopping program by switch statement 
<html>
<title> My Shoping Program </title>

<body bgcolor=yellow text=red>
<h1 align=center> Welcome In Our Restaurant </h1>
<form name=f>
<font size=5>
<pre>
1. Maggi Rs.35                         2. Samosa Rs.15
<br>
3. Cold drink Rs.45                   4. Pizza Rs.75

Enter choice (1-4): <input type=text name=c size=7>
</pre>
Enter quantity: <input type=text name=q size=5>
<input type=button value="Bill amount" onclick="bill()">
</form>
</body>

<script>
function bill()
{
var c,q,b;
c=Number(f.c.value);
q=Number(f.q.value);
switch(c)
{
case 1:
            b=q*35; break;
case 2:
            b=q*15; break;
case 3:
            b=q*45; break;
case 4:
            b=q*75; break;
default:
alter("Wrong choice");
}
alert("Total bill amount is:"+b)
}
</script>
</html>








Post a Comment

0 Comments