|
Conditional Statements
Very often when you write code, you want to perform different
actions for different decisions. You can use conditional
statements in your code to do this.
In VBScript we have two conditional statements:
· If...Then...Else statement - use this statement if you
want to select one of two sets of lines to execute
· Select Case statement - use this statement if you want
to select one of many sets of lines to execute
If....then.....else
You should use the IF statement if you want to execute some code
if a condition is true, or if you want to select one of two
blocks of code to execute.
If you want to execute only one statement when a condition is
true, use this syntax for the if...then...else statement, like
this:
If i = 10 Then msgbox "Hello"
Notice that there is no ..else.. in this syntax. You just tell
the code to perform one action if the condition (i) is
equal to some value (in this case the value is 10).
If you want to execute more than one statement when a condition
is true, use this syntax for the if...then...else statement,
like this:
If i = 10 Then
msgbox "Hello"
i = 11
more statements
End If
There is no ..else.. in this syntax either. You just tell the
code to perform multiple actions if the condition (i) is
equal to some value (in this case the value is 10).
If you want to execute some statements if a condition is true
and execute others if a condition is false, use this syntax for
the if...then...else statement, like this:
If i = 10 Then
msgbox "Hello"
i = 11
Else
msgbox "Goodbye"
End If
The first block of code will be executed if the condition is
true (if i is equal to 10), the other block will be executed if
the condition is false (if i is not equal to 10).
Select case
You should use the SELECT statement if you want to select one of
many blocks of code to execute.
Select Case payment
Case "Cash"
msgbox "You are going to pay cash"
Case "Visa"
msgbox "You are going to pay with visa"
Case Else
msgbox "Unknown method of payment"
End Select
This is how it works: First we have a single expression (most
often a variable), that is evaluated once. The value of the
expression is then compared with the values for each Case in the
structure. If there is a match, the block of code associated
with that Case is executed.
Examples
1.This example demonstrates how to write the if...then
statement.
Coding
<html>
<head>
<script language="VBScript">
function greeting()
i=hour(time)
if i < 10 then
msgbox("Good morning")
else
msgbox("Hello")
end if
end function
</script>
</head>
<body onload="greeting()">
</body>
</html>
2. This example demonstrates hoe to write the select case
statement.
Coding
<html>
<head>
<script language="VBScript">
function buy()
payment="Cash"
Select Case payment
Case "Cash"
msgbox "You are going to pay cash"
Case "Visa"
msgbox "You are going to pay with visa"
Case Else
msgbox "Unknown method of payment"
End Select
end function
</script>
</head>
<body onload="buy()">
</body>
</html>
|