Conditional Statements
Part:
1
2
3
(Continued from previous part...)
"If" Statement Example
To help you understand how "If" statements work, I wrote the following the example, condition_if.html:
<html>
<body>
<!-- condition_if.html
Copyright (c) 2006 by Dr. Herong Yang. http://www.herongyang.com/
-->
<pre>
<script language="vbscript">
' Single-statement "If"
bIsNewYear = True
document.writeln("")
If bIsNewYear Then document.writeln("Happy New Year!")
' Multi-statement "If"
bIsLogOn = True
document.writeln("")
If bIsLogOn Then
document.writeln("Open the log file.")
document.writeln("Write the log message.")
document.writeln("Close the log file.")
End If
' "If ... Else" statement
bIsAdmin = False
document.writeln("")
If bIsAdmin Then
document.writeln("Display the delete button.")
document.writeln("Display the edit button.")
Else
document.writeln("Display the view button.")
End If
' "If ... ElseIf" statement
iDay = 4
If iDay = 0 Then
sOpenHours = "closed"
ElseIf iDay >= 1 And iDay <=5 Then
sOpenHours = "open from 9:00am to 9:00pm"
ElseIf iDay = 6 Then
sOpenHours = "open from 9:00am to 5:00pm"
Else
sOpenHours = "undefined"
End If
document.writeln("")
document.writeln("The library is " & sOpenHours)
</script>
</pre>
</body>
</html>
Here is the output:
Happy New Year!
Open the log file.
Write the log message.
Close the log file.
Display the view button.
The library is open from 9:00am to 9:00pm
The output matches my expectation perfectly!
"Select Case" Statements
"Select Case" statement is an alternative way of executing statements selectively based on certain conditions.
Here is the syntax of "Select Case" statements:
Select Case test_value
Case expected_value_list_1
statement_block_1
Case expected_value_list_2
statement_block_2
...
...
Case Else
statement_block_n
End Select
where "test_value" is a value used to test against with expected values specified in the "Case" clauses,
and "expected_value_list_*" are lists of expected values. The execution of "Select Case" statement goes like this:
- Each "Case" clause will be visited sequentially from top to bottom.
- If one of the values in the expected value list equals to the test value in a "Case" clause,
the statement block in that clause will be executed.
- If the statement block of any "Case" clause gets executed, the entire statement ends.
- The "Case Else" clause is a special clause. Its statement block will be executed if and only if
no statement block of any other "Case" clauses gets executed.
(Continued on next part...)
Part:
1
2
3
|