VBScript If Statements

VBScript If statements are a handy tool for any VBScript programmer. In fact, If statements are a universal to all programming languages (that I'm aware of).

An If Statement allows you to tell your program to do something only if a condition is true.

For example, you might have a website that asks the user what color their hair is. You could write code that only executes if their hair is say, black. OK, that's a pretty lame example but you get the idea!

Example If Statement

In this example, we'll stick with the lame subject of hair color, but to keep it simple, we won't ask for user input. We'll just set a variable with a hair color values.

Copy to Clipboard
<script type="text/vbscript">
  Dim hairColor
  hairColor = "Black"
  If hairColor = "Black" Then
    document.write("Same color as my cat!")
  End If
</script>

This results in:

Same color as my cat!

If Else Statement

An If Else statement is an extension to the If statement. This allows you to tell the program to do something else in the event that the condition is not true.

Copy to Clipboard
<script type="text/vbscript">
  Dim hairColor
  hairColor = "Blue"
  If hairColor = "Black" Then
    document.write("Same color as my cat!")
  Else
    document.write("Oh well, whatever...")
  End If
</script>

This time the value of hairColor is blue. Because it is not black, the Else part of the statement is executed.

This results in:

Oh well, whatever...

Elseif Statement

You can add an Elseif to test for another condition if you like. You could do as many of these as you like too.

Copy to Clipboard
<script type="text/vbscript">
  Dim hairColor
  hairColor = "Blue"
  If hairColor = "Black" Then
    document.write("Same color as my cat!")
  Elseif hairColor = "Blue" Then
     document.write("Same color as my parrot!")
  Else
    document.write("Oh well, whatever...")
  End If
</script>

This time the Elseif code is executed because the value of the hairColor variable is blue.

This results in:

Same color as my parrot!

Enjoy this page?

Sponsored Link: Design CODE-FREE Websites

Check a Domain:

ZappyHost Logo
Webydo Banner Ad