What is VBScript

Share Embed Donate


Short Description

Download What is VBScript...

Description

What is VBScript? VBScript, Microsoft's Visual Basic Scripting Edition, is a scaled down version of Visual Basic. While it doesn't offer the functionality of Visual Basic, it does provide a powerful, easy to learn tool that can be used to add interaction to your web pages. If you are already experienced in either Visual Basic or Visual Basic for Applications, you will find working with VBScript easy and should be immediately productive . Don't be concerned if you haven't worked in another version of Visual Basic. VBScript is easy to learn, even for the novice developer. Adding VBScript to Web Pages Scripting languages, like JavaScript and VBScript, are designed as an extension to HTML. The web browser receives scripts along with the rest of the web document. It is the browser's responsibility to parse and process the scripts. HTML was extended to include a tag that is used to incorporate scripts into HTML-the HTML-the tag. The Tag You add scripts into your web pages within a pair of  of  tags. The tag signifies the start of the script section, while marks the end. An example of this is shown below: Working With VBScript MsgBox "Welcome to my Web page!"

The beginning tag includes a LANGUAGE argument LANGUAGE  argument that indicates the scripting language that will be used. The LANGUAGE argument LANGUAGE  argument is required because there is more than one scripting language. Without the LANGUAGE argument, LANGUAGE argument, a web browser would not know if the text between the tags was JavaScript, VBScript or another scripting language. While technically you can place scripts throughout an HTML document using pairs of  tags, typically scripts are often found at either the top or bottom of a Web document. This provides for easy reference and maintenance. Handling Non-Supporting Browsers Not all browsers support scripting languages. Some only support JavaScript. Only Microsoft's Internet Explorer supports VBScript. You might be wondering what happens to your scripts when non-supporting browsers encounter them. Usually browsers will do what they do most frequently with text, they will display your scripts as part of the web page. Obviously, this isn't the result you had hoped for. One simple way to address this problem is to encase your scripts in comment tags

(). -->). Below is our example script as it appears with the addition of the comment tags: Working With VBScript

Now, when a browser that does not support VBScript processes this page, it will view your script as a comment and simply ignore it. Working with Variables A variable is a named location in computer memory that you can use for storage of  data during the execution of your scripts. You can use variables to: •

Store input from the user gathered via your web page



Save data returned from functions



Hold results from calculations

 An Introduction to Variables Let's look at a simple VBScript example to clarify the use of variables. Sub cmdVariables_OnClick Dim Name Name = InputBox("Enter your name: ") MsgBox "The name you entered was " & Name End Sub

The first line of this example defines a sub procedure p rocedure associated with the click event of a command button named cmdVariables. cmdVariables .

On the second line we declare a variable named Name. Name. We are going to use this variable to store the name of the user when it is entered. The third line uses the InputBox function InputBox function to first prompt for, and then return, the user's name. You will see more of the InputBox function InputBox function later in this tutorial. The name it returns is stored in the Name variable. The fourth line uses the MsgBox function MsgBox function to display the user's name. Finally, the sub procedure completes on line five. Exactly how, and where, variables are stored is not important. What you use them for, and how you use them is important. That is what we will be looking at next. Declaring Variables There are two methods for declaring variables in VBScript, explicitly and implicitly. You usually declare variables explicitly with the Dim statement: Dim Name

This statement declares the variable Name. Name. You can also declare multiple variables on one line as shown below, although it is preferable to declare each variable separately: Dim Name, Address, City, State

Variables can be declared implicitly by simply using the variable name within your script. This practice is not recommended. It leads to code that is prone to errors and more difficult to debug. You can force VBScript to require all variables to be explicitly declared by including the statement Option Explicit at Explicit  at the start of every script. Any variable that is not explicitly declared will then generate an error. Variable Naming Rules When naming variables the following rules apply: •

They must begin with an alphabetic character



They cannot contain embedded periods





They must be unique within the same scope. There is more on scopes later in this lesson They must be no longer than 255 characters

Variants and Subtypes VBScript has a single data type called a variant . Variants have the ability to store different types of data. The types of data that a variant can store are referred to as subtypes. subtypes . The table below describes the subtypes supported by VBScript.

Subtype

Description of Uses for Each Subtype

Byte

Integer numbers between 0 to 255

Boolean

True

and  False

Curren Currency cy Monetar Monetary y values values Date

Date and time

Double Double

Extrem Extremely ely large large number numberss with with decima decimall poin points ts

Empt Empty y

The The value value that that a var varian iantt hold holdss befo before re bein being g used used

Error

An error number  

Integ Integer er

Larg Largee integ integer erss betw betwee een n -32, -32,76 768 8 and and 32,7 32,767 67

Long Long

Extr Extrem emely ely larg largee inte intege gers rs (-2 (-2,1 ,147 47,4 ,483 83,6 ,648 48 and and 2,1 2,147 47,4 ,483 83,6 ,647 47))

Object

Objects

Null

No valid data

Sing Single le

Larg Largee num numbe bers rs with with deci decima mall poi point ntss

String

Character st strings

 Assigning Values You assign a value to a variable by using the following format: Variable_name = value

The following examples demonstrate assigning values to variables: Name = "Larry Roof" HoursWorked = 50 Overtime = True

Scope of Variables The scope of a variable dictates where it can be used in your script. A variable's scope is determined by where it is declared. If it is declared within a procedure, it is referred to as a procedure-level  a procedure-level variable variable and can only be used within that procedure. If it is declared outside of any procedure, it is a script-level variable script-level variable and can be used throughout the script. The example below demonstrates both script-level and procedure-level variables. Dim counter Sub cmdButton_onClick Dim temp End Sub

The variable counter is counter is a script-level variable and can be utilized throughout the script. The variable temp exists only within the cmdButton_onClick  sub-procedure. cmdButton_onClick sub-procedure. Constants VBScript does not provide support for constants, such as you find in other programming languages. You can work around this by assigning values to variables that you have defined as shown in the example below. Here, TAX_RATE is TAX_RATE  is our constant. Dim TAX_RATE TAX_RATE = .06 Function CalculateTaxes CalculateTaxes = CostOfGoods * TAX_RATE End Function

 Arrays The VBScript language provides support for arrays. You declare an array using the Dim statement, just as you did with variables: Dim States(50)

The statement above creates an array with 51 elements. Why 51? Because VBScript arrays are zero-based  are zero-based , meaning that the first array element is indexed 0 and the last is the number specified when declaring the array. You assign values to the elements of an array just as you would a variable, but with an additional reference (the index) to the element in which it will be stored: States(5) = "California" States(6) = "New York"

Arrays can have multiple dimensions-VBScript supports up to 60. Declaring a two dimensional array for storing 51 states and their capitals could be done as follows: Dim StateInfo(50,1)

To store values into this array you would then reference both dimensions. StateInfo(18,0) = "Michigan" StateInfo(18,1) = "Lansing"

VBScript also provides support for arrays whose size may need to change as the script is executing. These arrays are referred to as dynamic arrays dynamic  arrays.. A dynamic array is declared without specifying the number of elements it will contain: Dim Customers()

The ReDim statement is then used to change the size of the array from within the script: ReDim Customers(100)

There is no limit to the number of times an array can be re-dimensioned during the execution of a script. To preserve the contents of an array when you are redimensioning, use the Preserve keyword: ReDim Preserve Customers(100)

Objects and VBScript Objects, both in the form of Java applets and ActiveX controls, enhance the functionality that is provided with HTML. By using VBScript you can extend the capabilities of these controls, integrating and manipulating them from within your scripts. In this lesson we will look at how you can utilize the power of objects with VBScript. Scripting with objects involves two steps: •

Adding the object to your web page using HTML



Writing script procedures to respond to events that the object provides

 Adding Objects to Your Web Pages Since this is a VBScript tutorial, rather than an HTML tutorial, we will offer only a limited discussion of how to add an object to a web page. Objects, whether they're Java applets or ActiveX controls are added to a page with the tag. The properties, or characteristics, of the object are configured using the tag. Typically you will see an object implemented using a single tag along with several tags. The following HTML code demonstrates how an ActiveX control might appear when added to a page:

Linking VBScript with Objects Once you have added a control to your web page, it can be configured, manipulated and responded to through its properties, methods and events. Properties are the characteristics of an object. They include items like a caption, the foreground color and the font size. Methods cause an object to perform a task. Events are actions that are recognized by an object. For instance, a command button recognizes an onclick event. onclick event. Note

The Script Wizard found in the Microsoft ActiveX Control Pad can be used to identify events provided by a control, and to generate script to respond to these events. For the most part, you will be focusing on properties and events. An example of  setting properties for a label control is shown in the following example. Sub cmdCalculatePay_onClick

Dim HoursWorked Dim PayRate Dim TotalPay HoursWorked = InputBox("Enter hours worked: ") PayRate = InputBox("Enter pay rate: ") TotalPay = HoursWorked * PayRate lblTotalPay.caption = TotalPay End Sub

The caption property of the label control, lblTotalPay , is set equal to the results of  our calculation with the script line: document.frmPayrate.lblTotalPay.caption = TotalPay

Object properties are referenced within your scripts using the same f ormat shown in Exercise 2. Controlling Your VBScript Routines VBScript allows you to control how your scripts process data through the use of  conditional and 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 If statement in theory, we will examine some examples to see how they work. The simplest version of an If statement If statement is one that contains only a condition and a single statement:

If AmountPurchased > 10000 Then DiscountAmount = AmountPurchased * .10

In this example statement the condition is: If AmountPurchased > 10000

which simply checks to see if the contents of the variable AmountPurchased  variable AmountPurchased is is greater than ten thousand. If it is, the condition is true. In this simple version of the If statement If statement when the condition is true the following statement is executed: DiscountAmount = AmountPurchased * .10

Next we will look at a more complicated version of the If statement. 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 - DiscountAmount End If

In this form of the If statement, If statement, one or more statements can be executed when the condition is true, by placing them between the If statement If statement on top and the End If  End If  statement on the bottom. The next form of the If statement If statement uses the If..Then..Else format. This version of the If statement 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 - DiscountAmount Else HandlingFee = AmountPurchased *.03 Subtotal = AmountPurchased + HandlingFee End If

In 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 If statement that we will look at is the If..Then..Else If . In this form the If statement 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 - DiscountAmount Else If AmountPurchased > 5000 Then DiscountAmount = AmountPurchased * .05 Subtotal = AmountPurchased - DiscountAmount Else HandlingFee = AmountPurchased *.03 Subtotal = AmountPurchased + HandlingFee End If

In 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. If statements. Select Case

The Select Case 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 If statement the Select Case Select Case structure checks a condition, and based upon that condition being true, executes a series of  statements. The syntax of the Select Case Select Case statement is: Select Case condition Case value Case value ... Case Else End Select

For example, the following Select statement 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 = .02 End Select

The Select Case 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. 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. Using VBScript with Forms As the popularity of web page forms increase, so does the need to be able to validate data before the client browser submits it to the web server. As a scripting language, VBScript is well suited for this task. Once the form has been validated, the same script can be used to forward the data on to the server. In this lesson we will look at both the process of validating and submitting forms. Validating Your Forms

The process of validating forms involves checking the form to see if: •

All of the required data is proved



The data provided is valid

Meticulous data validation scripts can be tedious to code but are well worth their return in verifying the quality of the data. The validation example that we will be examining does not contain anything new in the way of VBScript. We are simply using the elements that we have learned in the previous lessons in a new way. Before reading any further you may find if beneficial to ponder how you would validate an HTML form using the VBScript techniques that you have learned. Okay, are you through pondering? Let's look at an example to give you an idea of  what is possible when it comes to validating forms.

Checking Form Input

This example is pretty simple. It has a single field in which the user can enter their age and a single command button that is used to submit their age to the server. A copy of this example can be found in exam_5a.htm. exam_5a.htm . Working With VBScript: Example 5a A VBScript Example on Variables This example demonstrates validation techniques in VBScript. Enter your age:

How It Works

The heart of this validation script is found in the click event procedure for the cmdSubmit command cmdSubmit  command button. We start by checking if the user entered anything at all into the field using VBScript's Len function. This function returns the length of a string. If the length is 0, the data is invalid. We inform the user and exit the submit procedure via the Exit Sub Exit Sub statement: ' Check to see if the user entered anything.

If (Len(document.frmExample5a.txtAge.value) = 0) Then MsgBox "You must enter your age before submitting." Exit Sub End If

Next we check to see if what the user entered is a numeric value. The VBScript function IsNumeric returns IsNumeric returns a true value when it is a number. If not, we tell the user and exit: ' Check to see if the user entered a number. If (Not(IsNumeric(document.frmExample5a.txtAge.value))) Then MsgBox "You must enter a number for your age." Exit Sub End If

Our final check involves verifying that the age they entered seems reasonable for our environment. I have determined that no age less than 0 or greater than 100 is acceptable. Using an If..Then statement we can check the value of the input field against this criteria: ' Check to see if the age entered is valid. If (document.frmExample5a.txtAge.value < 0) Or _ (document.frmExample5a.txtAge.value > 100) Then MsgBox "The age you entered is invalid." Exit Sub End If

That's it. While this example is by no means the most detailed validation script you will encounter it provides you with a basis of what is possible with VBScript. Submitting Your Forms

Compared to validation, the process of submitting a form is simple. In our example we've used a normal HTML button with the Submit caption Submit caption that is tied to an event procedure that both validates and at the same time submits the form. In Chapter 5, we've demonstrated how to use function MyButton_onSubmit , as an alternative. The code that we would have to add to our previous example to submit the form is shown below: ' Data looks okay so submit it. MsgBox "Thanks for providing your age."

document.frmExample5a.submit

The MsgBox statement MsgBox statement lets the user know that their data has been processed. The form is then submitted by invoking the Submit method Submit method of the form object. As we saw in lesson 3 on objects, methods cause an object to perform p erform a task. Here we are using the submit method submit  method of our form to cause the form to submit its data, just as if  we had used a submit control. submit control. Applet width=200>*/ import java.applet.*; import java.net.*; import java.awt.*; public class InJava4 extends Applet{ String msg; public void init(){ setBackground(Color.red); msg = "Hello from Java (using javascript alert)"; } public void paint(Graphics g) { g.drawString(msg,10,20); } } width=200>

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF