VBScript allows you to control how your scripts process data through the use of conditional and looping statements. By using conditional statements you can develop scripts that evaluate data and use criteria to determine what tasks to perform. Looping statements allow you to repetitively execute lines of a script. Each offers benefits to the script developer in the process of creating more complex and functional web pages.
Conditional Statements
VBScript provides two forms of conditional statements:
If..Then..Else
Select..Case
If..Then..Else
The If..Then..Else statement is used, first to evaluate a condition to see if it is true or false and second, depending upon the condition, to execute a statement or set of statements. Rather than discussing an If statement in theory, we will examine some examples to see how they work.
The simplest version of an If statement is one that contains only a condition and a single statement:
If AmountPurchased > 10000 Then
DiscountAmount = AmountPurchased * .10In this example statement the condition is:
If AmountPurchased > 10000which simply checks to see if the contents of the variable AmountPurchased is greater than ten thousand. If it is, the condition is true. In this simple version of the If statement when the condition is true the following statement is executed:
DiscountAmount = AmountPurchased * .10Next we will look at a more complicated version of the If statement. In this version we will perform a series of statements when the condition is true:
If AmountPurchased > 10000 Then DiscountAmount = AmountPurchased * .10 Subtotal = AmountPurchased - DiscountAmountEnd IfIn this form of the If statement, one or more statements can be executed when the condition is true, by placing them between the If statement on top and the End If statement on the bottom.
The next form of the If statement uses the If..Then..Else format. This version of the If statement differs from the two previous versions in that it will perform one set of statements if the condition is true and another set when the condition is false:
If AmountPurchased > 10000 Then DiscountAmount = AmountPurchased * .10 Subtotal = AmountPurchased - DiscountAmountElse HandlingFee = AmountPurchased *.03 Subtotal = AmountPurchased + HandlingFeeEnd IfIn this example when the condition is true, that is the customer's order is over $10,000, they receive a 10% discount. When the order is under $10,000, they are charged a 3% handling fee.
The final version of the If statement that we will look at is the If..Then..Else If. In this form the If statement checks each of the conditions until it either finds one that is true or an Else statement:
If AmountPurchased > 10000 Then DiscountAmount = AmountPurchased * .10 Subtotal = AmountPurchased - DiscountAmountElse If AmountPurchased > 5000 Then DiscountAmount = AmountPurchased * .05 Subtotal = AmountPurchased - DiscountAmountElse HandlingFee = AmountPurchased *.03 Subtotal = AmountPurchased + HandlingFeeEnd IfIn this example the customer receives a 10%discount for orders over $10000, a 5% discount for orders over $5000 and a handling fee of 3% for orders under $5000.
As you see, VBScript offers you plenty of options when it comes to If statements.
Select Case
The Select Case statement provides an alternative to the If..Then..Else statement, providing additional control and readability when evaluating complex conditions. It is well suited for situations where there are a number of possible conditions for the value being checked. Like the If statement the Select Case structure checks a condition, and based upon that condition being true, executes a series of statements.
The syntax of the Select Case statement is:
Select Case condition Case value Case value ... Case ElseEnd SelectFor example, the following Select statement assigns different shipping fees based upon the State where the order is being sent:
Select Case Document.frmOrder.txtState.Value Case "California" ShippingFee= .04 Case "Florida" ShippingFee = .03 Case Else ShippingFee = .02End SelectThe Select Case statement checks each of the Case statements until it finds one that will result in the condition being true. If none are found to be true, it executes the statements within the Case Else.
Note
Even though it is not required, always include a Case Else when working with Select Case statements to process conditions that you may not have considered possible. For these conditions you can display something as simple as a message dialog to inform you that a branch was executed that you hadn't planned for.
VBScript provides four forms of looping statements:
The variable counter is the numeric value being incremented or decremented. The number 1, defines the start of the loop, 12 the end of the loop. When this loop executes it will display twelve dialog box messages, each containing the product of multiplying five times the counter as it runs from 1 to 12.
In this example, the variable counter is incremented by 1 with each loop. Optionally, we could control how we wanted the counter to be modified through the addition of the Step argument:
This slight modification to the loop results in only the products of the odd numbers between 1 and 12 being displayed. If you want to create a countdown loop, where the number is decremented with each loop simply use a negative value with the Step argument as shown in the following example:
Note that in a decrementing loop the starting number is greater than the ending number.
Or at the end of the loop as shown in the following example:
The difference between these two formats is that the first example may never perform the statements included within its structure while the second example will always perform its statements at least once.
Or at the end of the loop as shown in the following example:
One use for a Do..Loop is shown in the example below:
In this example we ask the user to enter a password before performing the conditional part of the Do..Loop the first time. The result is that, if they enter the correct password the first time, the statements within the loop's structure will never be performed. If the user were to enter an invalid password then the statements within the Do..Loop structure would be performed, a message would be displayed and the user would be prompted to re-enter their password.
The structure for the While..Wend statement is:
- For..Next
- For Each..Next
- Do..Loop
- While..Wend
For..Next
The For..Next structure is used when you want to perform a loop a specific number of times. It uses a counter variable, which is incremented or decremented with each repetition of the loop. The following example demonstrates a simple For loop:For counter = 1 To 12 result = 5 * counter MsgBox counter & " times 5 is " & resultNext counterThe variable counter is the numeric value being incremented or decremented. The number 1, defines the start of the loop, 12 the end of the loop. When this loop executes it will display twelve dialog box messages, each containing the product of multiplying five times the counter as it runs from 1 to 12.
In this example, the variable counter is incremented by 1 with each loop. Optionally, we could control how we wanted the counter to be modified through the addition of the Step argument:
For counter = 1 To 12 Step 2 result = 5 * counter MsgBox counter & " times 5 is " & resultNext counterThis slight modification to the loop results in only the products of the odd numbers between 1 and 12 being displayed. If you want to create a countdown loop, where the number is decremented with each loop simply use a negative value with the Step argument as shown in the following example:
For counter = 12 To 1 Step -1 result = 5 * counter MsgBox counter & " times 5 is " & resultNext counterNote that in a decrementing loop the starting number is greater than the ending number.
For Each..Next
The For Each..Next is similar to the For..Next loop but instead of repeating a loop for a certain number of times, it repeats the loop for each member of a specified collection. The discussion of collections and their use is outside of the scope of this tutorial. The For Each..Next structure is detailed elsewhere in the book.Do..Loop
The Do..Loop structure repeats a block of statements until a specified condition is met. Normally, when using a Do..Loop, the condition being checked is the result of some operation being performed within the structure of the loop. Two versions of this structure are provided the Do..While and the Do..Until.Do..While
A Do loop that contains the While keyword will be performed as long as the condition being tested is true. You have the option of checking the condition at the start of the loop, as in the form:Do While conditionstatementstatement...LoopOr at the end of the loop as shown in the following example:
Dostatementstatement...Loop While conditionThe difference between these two formats is that the first example may never perform the statements included within its structure while the second example will always perform its statements at least once.
Do..Until
A Do loop that contains the Until keyword will continue to loop as long as the condition being tested is false. As with the Do..While structure, you have the option of checking the condition at the start of the loop as in the form:Do Until condition statement statement ...LoopOr at the end of the loop as shown in the following example:
Do statement statement ...Loop Until conditionOne use for a Do..Loop is shown in the example below:
password = InputBox("Enter your password:")Do Until password = "letmein" Msgbox "Invalid password - please try again." password = InputBox("Enter you password:")LoopIn this example we ask the user to enter a password before performing the conditional part of the Do..Loop the first time. The result is that, if they enter the correct password the first time, the statements within the loop's structure will never be performed. If the user were to enter an invalid password then the statements within the Do..Loop structure would be performed, a message would be displayed and the user would be prompted to re-enter their password.
While..Wend
The While..Wend structure loops as long as the condition being checked is true. If the condition is true, the While..Wend statement operates similar to the Do..Loop structure but without its flexibility.The structure for the While..Wend statement is:
While conditionstatementstatement...Wend In this exercise we continue to extend the functionality of our web page. New features provided by this exercise are:
- A combo box from which the user can select products
- Automatic pricing of products as they are selected
- Discounting purchase prices based upon the size of the order
As with the first three exercises simply follow the step-by-step instructions below to begin to learn how to use conditional and looping statements with your scripts.
Exercise 4: Working with Objects
In this exercise you will create an HTML document which contains a script that will retrieve data from a web page, perform calculations and output a result back to the web page. Additionally it will look up prices for products and provide discounts based upon the order size.
Testing the HTML Document
Open up a text editor application and load the file exer4_v1.html. This is the HTML component of this exercise already typed in for you.
Look over the HTML document. Note the addition of an ActiveX combo box control, cmbProducts, and additional label controls. Scroll to the bottom of the document where you will find a script that fills the combo box with the available products as shown in the following code fragment.
<SCRIPT LANGUAGE="VBScript">
<!--
document.frmExercise4.cmbProducts.addItem "NEC MultiSync E1100"
document.frmExercise4.cmbProducts.addItem "NEC MultiSync P1150"
document.frmExercise4.cmbProducts.addItem "NEC MultiSync E750"
-->
</SCRIPT>
Test the file by loading it into Internet Explorer. The resulting page is shown below. You can forget about testing the Calculate Cost button, we've been down that road before.
We will now add a script to provide functionality for the Calculate Cost command button, as well as when a product is selected from the combo box control.
Adding VBScript
A completed copy of this part of the exercise can be found in the file exer4_v2.html.
Modify the document by adding the shaded lines of script:
<HTML>
<HEAD>
<TITLE>Working With VBScript: Exercise 4</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!-- Add this to instruct non-IE browsers to skip over VBScript modules.
Option Explicit
Sub cmdCalculate_OnClick
Dim AmountofDiscount
Dim AmountofTax
Dim DISCOUNT_LIMIT
Dim DISCOUNT_RATE
Dim SubtotalBefore
Dim SubtotalAfter
Dim TAX_RATE
Dim TotalCost
' Define our constant values.
DISCOUNT_LIMIT = 1000
DISCOUNT_RATE = .10
TAX_RATE = 0.06
' Calculate the subtotal for the order.
SubtotalBefore = document.frmExercise4.txtQuantity.value _
* document.frmExercise4.lblUnitCost.caption
' Check to see if the order is large enough to offer discounts.
If (SubtotalBefore > DISCOUNT_LIMIT) Then
AmountofDiscount = SubtotalBefore * DISCOUNT_RATE
Else
AmountofDiscount = 0
End If
SubtotalAfter = SubtotalBefore - AmountofDiscount
' Calculate taxes and total cost.
AmountofTax = SubtotalAfter * TAX_RATE
TotalCost = SubtotalAfter + AmountofTax
' Display the results.
document.frmExercise4.lblSubtotalBefore.caption = SubtotalBefore
document.frmExercise4.lblDiscount.caption = AmountofDiscount
document.frmExercise4.lblSubtotalAfter.caption = SubtotalAfter
document.frmExercise4.lblTaxes.caption = AmountofTax
document.frmExercise4.lblTotalCost.caption = TotalCost
End Sub
Sub cmbProducts_Change()
Select Case document.frmExercise4.cmbProducts.value
Case "NEC MultiSync E1100"
document.frmExercise4.lblUnitCost.caption = 1590
Case "NEC MultiSync P1150"
document.frmExercise4.lblUnitCost.caption = 880
Case "NEC MultiSync E750"
document.frmExercise4.lblUnitCost.caption = 1940
Case Else
document.frmExercise4.lblUnitCost.caption = 0
End Select
End Sub
-->
</SCRIPT>
</HEAD>
...
Save the file, and test it in Internet Explorer. Select a product from the combo box. Notice how the Unit Cost field is automatically updated as shown below.
Enter 10 into the Quantity field. Try out the Calculate Cost button. The result is shown below.
How It Works
Exercise 4 has two new features, the automatic price lookup and the discount feature. We will look at how each is implemented separately.
Product Lookup
The lookup feature is implemented via the cmbProducts_Change event procedure. As you might have remembered, the ActiveX combo box control that we added to your HTML document was given the name cmbProducts. This control supports a change event, which is triggered every time the user selects an item from the list. We simply make use of the Select Case statement to check the value of the control. Now, in our example, these values are hard coded. In a real life application we would normally pull these from a data source.
Sub cmbProducts_change()
Select Case document.frmExercise4.cmbProducts.value
Case "NEC MultiSync E1100"
document.frmExercise4.lblUnitCost.caption = 1590
Case "NEC MultiSync P1150"
document.frmExercise4.lblUnitCost.caption = 880
Case "NEC MultiSync E750"
document.frmExercise4.lblUnitCost.caption = 1940
Case Else
document.frmExercise4.lblUnitCost.caption = 0
End Select
End Sub
Note
Even though the combo box control can only contain one of the three monitors, we still employ a Case Else branch. This is simply a good programming habit to develop. Discounting Orders
The script used to implement discounts begins by defining some constants, setting the discount limit at $1000 and a discount rate of 10%. Our discounting process begins by calculating the subtotal of the order before discounts and taxes are applied.
Discounting is then applied through the use of an If..Then..Else statement. We compare our subtotal amount against the constant DISCOUNT_LIMIT. If our amount is greater than the limit, the discount amount is calculated and stored in the variable AmountofDiscount. If it is less than, or equal to, the limit, the discount amount is set to 0.
' Check to see if the order is large enough to offer discounts.
If (SubtotalBefore > DISCOUNT_LIMIT) Then
AmountofDiscount = SubtotalBefore * DISCOUNT_RATE
Else
AmountofDiscount = 0
End If
The value of the variable AmountofDiscount is subsequently subtracted from the subtotal. Next we calculate the taxes and total cost of the order. We complete the script by displaying the order information on the web page.
Extending this application
In this example I set the discount limit at $1,000. What would we have to change in our script to set the limit at a more reasonable amount of say, $100,000?
Summary
Can you believe how far our original application has progressed? Now we have a page that receives user input, performs price lookups, calculates discount amounts and displays the complete order information on the web page, all without having to go back to the web server.
In this chapter you were introduced to:
- Conditional statements, which allow you to selectively execute blocks of statements
- Looping statements that provide you with a way to repetitively execute blocks of statements
Now that we can input, manipulate and display data, it is time to learn how to validate the data, before sending it on to a web server.
No comments:
Post a Comment