Ticker

6/recent/ticker-posts

JavaScript (If Else Statement)

IF ELSE STATEMENT IN JAVASCRIPT

The IF-Else statement is used to implement at-most two conditions.



EXAMPLE 1: Program to find largest number among two entered values.

<html>
<title> Program to find largest number </title>
<body>
<form name="f">
Enter first number <input type="text" name="n1">
<br> <br>
Enter second number <input type="text" name="n2">
<input type="button" value="Largest" onclick="Large()">
</form>

<script>
function Large()
{
var a,b;
// Access first text box value in 'a' variable
a=f.n1.value

// Access first text box value in 'a' variable
b.f.n2.value;

// Implement condition by if statement 
if(a > b)
alert("Largest value is: "+a);
else
alert("Largest value is: "+b);
}
</script>
</body>
</html>


EXAMPLE 2: Program to find even or odd number.
<html>
<title> Program to find even or odd number </title>
<body>
<form name="f">
Enter any number <input type="text" name="num">
<br> <br>
<input type="button" value="Even or Odd" onclick="check()">
</form>

<script>
function check()
{
var n;

n=f.num.value;

// Implement condition by if statement
if(n%2==0)
alert("Even value");
else
alert("Odd value");
}
</script>
</body>
</html>


EXAMPLE 3: Program to find leap year.

<html>
<title> Program to find leap year </title>
<body>
<form name="f">
Enter any year <input type="text" name="y">

<input type="button" value="Leap year" onclick="year()">
</form>

<script>
function year()
{
var y;
y=f.y.value

if(y%4 == 0)
alert("Leap year");
else
alert("Not a leap year");
}
</script>
</body>
</html>






Post a Comment

0 Comments