VB Script Conditional Statements
In previous example, if you do not type in the text fields and click ok, the computer will go ahead and write empty strong. We can more than enforce the user to enter string value into the fields or make certain decisions about the provided values using if statements, we can see if the value is number, string, and make decisions of the response. If statement and case statement can be used for this purpose. Here is a syntax for if statement:
if a=n then do some thing - This is a single if statment responds on one condition
if a =n then
do some thing
else
do something else
end if
- This if statement does specific task when a = n and does other task when a is not equal to n.
if a = 8 then
msgbox"The number is 8"
elseif a = 7 then
msgbox"The number is 7"
elseif a = 6 then
msgbox"The number is 6"
else
msgbox"The number is not 8, 7, or 6"
end if - This is a nested if statement that can make wide range of decisions depend on what conditon is true.
The following example uses if statement to validate users response from previous example. This time we are using form fields. See forms to learning how to do them.
<html>
<head>
<script language="vbscript">
sub GetUserName()
dim firstName
dim lastName
firstName=form.txtfirstName.value
lastName=form.txtlastName.value
if firstName="" then
msgbox("Please type your first name")
elseif lastName="" then
msgbox("Please type your last name")
else
msgbox("Your name is: "&firstName&" "&lastName)
end if
end sub
</script>
</head>
<body>
<form name="form">
First Name: <input type="text"name="txtfirstName"><br>
Last Name: <input type="text"name="txtlastName"><br>
<input type="button" value="Click" onclick="call GetUserName()">
</body>
</html>
| We created two text fields in a form, txtfirstName and txtlastName. The name of the form is "form". We set variables firstName and lastName to the value of it's corresponding text field using the form name, field name, and value. We use if statement to check if the two variable have values. If the text fields have value then variables have values too because they are equal to the text fields. We checked firstName first, if it does not have value then, we display message box informing the user to enter their first name. If it has value then the condition is true and the control passes to lastName. We do the same for the last name, if it passes then msgbox displays whatever in the text fields. Here is the result of this example:
|
|