Lesson 2: Using Microsoft VBScript for Client-Side Scripting

VBScript Language Syntax

You can use VBScript to set properties and methods of ActiveX controls and Java applets that are contained within an HTML page.

The syntax of VBScript is identical to that of Visual Basic for Applications. However, VBScript is designed to download quickly over the Internet, so many language and run-time elements supported by Visual Basic for Applications are not supported under VBScript. Also, some language elements, such as file I/0, have been removed for security purposes.

Inherent Visual Basic Functions

VBScript supports some inherent, or built-in, Visual Basic functions, such as Msgbox , Date , and IsNumeric .

Example

In this VBScript example, a message box is displayed if the variable "Var" is numeric:
 If IsNumeric(Var) Then  MsgBox "Var is a number." End If 

In addition, some functions are implemented differently in VBScript. The Visual Basic Format function can be called in one of four specific versions in VBScript:

  • FormatCurrency
  • FormatDateTime
  • FormatNumber
  • FormatPercent

Note

For a complete reference of all functions that are supported by VBScript 2.0, refer to the VBScript Web site (www.microsoft.com/vbscript) or the Internet Client SDK.


Defining Procedures

VBScript features two kinds of procedures: Sub procedures and function procedures. As with all VBScript code, procedures must be placed within the <SCRIPT> tag to be recognized by the script interpreter and other procedures within the HTML page.

Sub Procedures

A sub procedure is a series of VBScript statements that are enclosed by the Sub and End Sub statements. It performs actions but does not return a value. A sub procedure can take arguments (constants, variables , or expressions that are passed by a calling procedure).

Example

In this example, a sub procedure is used to increment the sales variable by the value passed in NumSales :
 Sub IncreaseSales(NumSales) Sales = Sales + NumSales End Sub 

To call a sub procedure from another procedure, type the name of the procedure along with values for any required arguments, separating each with a comma. The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses:

 IncreaseSales 100 -or- Call IncreaseSales(100) 

Function Procedures

A function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A function procedure is similar to a sub procedure, but can return a value. A function procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). If a function procedure has no arguments, its Function statement must include an empty set of parentheses. A function procedure returns a value by assigning a value to its name in one or more statements. The return type of a function procedure is always a Variant data type.

Example

This example declares a function procedure that verifies a date value. An example of how to call this function is then shown:
 Function Validate(myDate) If IsDate(myDate) Then Validate = True Else Validate = False End If End Function 'Event procedure called when user clicks button named cmdTest Sub cmdTestDate_OnClick() Results = Validate(myDate) End Sub 

* To create a Web in Microsoft FrontPage 98
  1. Start FrontPage 98.
  2. Select Create a New FrontPage Web and click OK .
  3. Select One Page Web , change the title to Exercise9 , and click OK .
* To edit the Home Page
  1. Double-click on the Home Page icon to open the FrontPage Editor .
  2. From the Insert menu, highlight Form Field and click One Line Textbox .
  3. Right-click on the Submit button and choose Form Field Properties .
  4. Change the Name property to btnSquareIt .
  5. Change the Value/Label property to Square .
  6. Change the Button Type property to Normal , then click OK .
  7. Click on the Reset button and press the Delete key to remove it.
  8. Right-click on the Square button and choose Form Properties .
  9. Change the Form Name to Form1 , then click OK .
* To add VBScript to your Home Page
  1. Position the cursor next to the Square button on the Form.
  2. From the Insert menu, highlight Advanced , Click Script .
  3. Type the following VBScript code then click OK .
     Function SquareIt(Num) SquareIt = (Num * Num) End Function 
  4. Right-click on the Submit button and choose Script Wizard .
  5. On the tree control, expand the Form1 object, then expand the btnSquareIt object.
  6. Click on the btnSquareIt OnClick event, and select Code View on the bottom of the dialog box.
  7. Type the following code for the OnClick event, then click OK :
     Dim Result On Error Resume Next Result = SquareIt(T1.Value) MsgBox T1.Value & " squared = " & Result 
* To test your work
  1. After you have saved your work, from the File menu, click Preview in Browser .
  2. When your Web page appears in Internet Explorer, type an integer into the text box and click Square .

    The number you typed into the text box will be processed by the function you created (SquareIt). The result is then displayed in a message box.

  3. Close Internet Explorer and FrontPage 98.

Using Variables

Much like Visual Basic, VBScript supports the use of variables. VBScript supports data types, scope, and constants. A variable is a convenient placeholder that refers to a computer memory location where you can store program information that may change while your script is running. For example, you might create a variable called ClickCount to store the number of times a user clicks an object on a particular Web page. Where the variable is stored in memory is unimportant; however, it is important that you only have to refer to a variable by name to see its value or to change its value.

Data Types

VBScript supports only the Variant data type, which can hold different types of data, such as strings or numbers . In general, you can store the data you need in a Variant data type and the data will function appropriately.

To determine the type of data currently in the variable, you can use the VarType function.

To declare a variable in VBScript, you use the Dim statement.

Example

This example declares the variable myName :
 Dim myName 
Arrays VBScript also supports arrays. All arrays in VBScript are zero-based . The first index number in an array is always zero.

Example

This example declares an array that can store 11 values:
 Dim Students(10) 
Constants To create a constant in VBScript, use the Const statement. You can create string or numeric constants with meaningful names , and then assign literal values to them.

Example

This example uses the Const statement to declare two constants and assigns values to them:
 Const MYSTRING = "This is my string" Const MYAGE = 37 

Note

Use all uppercase letters when creating constants to differentiate them from variables.


Scope of Data Scope determines the place in a Web page from which a variable can be referenced. Two levels of scope, local scope and script-level scope, are used in VBScript.
  • Local scope

    If you declare a variable in a procedure, it has local scope. The variable is only available to the procedure. When the procedure terminates, the variable goes out of scope.

  • Script-level scope

    If you declare a variable outside of a procedure, it is available to all procedures on the Web page. This is referred to as script-level scope. A script-level variable maintains its value while the Web page is displayed in the browser.

A variable may be declared as either Public or Private when declared at script-level. Variables declared using the Public statement are available to all procedures in all scripts. However, Private variables are available only to the script in which they are declared. Variables declared with Dim at the script level are available to all procedures within the script. At the procedure level, variables are available only within the procedure.

You can also use the Dim , Public , or Private statements with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private , Public , or Dim statement, an error occurs.

Syntax

The following syntax is used when declaring variables:
 Dim varname  [([subscripts])]  Public varname  [([subscripts])]  Private varname  [([subscripts])]  
Example In this example, the variable X is available to all scripts and any corresponding procedures in the project. The Y variable, however, is available to the current script. Variable Z has scope only within the sub procedure MySub :
 <SCRIPT> Public X Private Y Sub MySub() Dim Z End Sub </SCRIPT> 

Note

When declaring variables, the Dim , Public , and Private statements in a procedure are generally used at the beginning of the procedure.


* To use variables in VBScript

  1. Open the Exercise9 Web in FrontPage 98.
  2. Open the Home Page in the FrontPage Editor.
  3. Place the cursor insertion-point inside the form on the Web page.
  4. From the Insert menu, highlight Advanced , then click Script .
  5. Type the following VBScript code into the code window:
     Option Explicit Private Y Sub SetValues() Dim X X = 1 Y = 1 End Sub Sub ChangeValuesAgain() X = 1 Y = 1 End Sub 
  6. Click Script Wizard .
  7. Expand the Window object on the tree control, and click the OnLoad event for the Window object.
  8. In the code window, type the following VBScript code, then click OK :
     SetValues ChangeValuesAgain 
  9. In the FrontPage Editor, click the Preview tab to view your Web page.

    Notice that you receive an error stating that the variable X is undefined. This is because X is only valid within the SetValues subroutine where it was declared using the Dim statement. However, the variable Y is in scope because it was declared as Private outside of a procedure.

  10. Click Yes to close the error dialog, then switch back to Normal view.
  11. Add the following line of code to the ChangeValuesAgain subroutine:
     Dim X 
  12. Save your work and preview your Web page.

    Notice that the error no longer occurs because X is now in scope due to the Dim statement that you just added in the ChangeValuesAgain subroutine.

  13. Close Internet Explorer and FrontPage 98.

Controlling Script Flow

Use Visual Basic statements to control how your script executes.

VBScript supports most of the Visual Basic for Applications structures for controlling program flow.

Looping Structures

Looping structures allow a block of script to run more than one time based on the condition of a variable or user input. The following looping statements are available in VBScript 2.0.
Statement Description
Do Loop Loops while or until a condition is True.
While Wend Loops while a condition is True.
For Next Uses a counter to run statements a specified number of times.

Example

This example creates an array and fills it with values:
 Dim x(10) For i = 1 to 10 x(i) = i * 10 Next 

Conditional Branching

Conditional branching controls if and when a certain block of script executes. This is dependent on the condition of variables or user input. Conditional branching differs from looping structures in that script in a conditional branch runs only once. The following conditional branching statements are available in VBScript 2.0.
Statement Description
If Then Execute code based on a whether a statement is true or false.
Select Case Execute code based on the value of a variable.

You can use the If ... Then ... Else statement to evaluate whether a condition is True or False and, depending on the result, specify one or more statements to run.

Example

This If ... Then ... Else statement calculates a bonus percentage based on the value of the Sales variable:
 If Sales > 100000 Then Bonus = .10 ElseIf Sales > 50000 Then Bonus = .05 Else Bonus = .02 End If 

VBScript 2.0 now supports the use of the Select Case statement. Select Case statements are useful when the variable being interrogated could contain more than two different values. Although your code can use embedded If Then statements, Select Case is typically easier to read and maintain.

Example

This example uses the variable Sales to determine the appropriate bonus:
 Select Case Sales Case 100000 Bonus = .1 Case 50000, 75000 Bonus = .05 Case Else Bonus = .02 End Select 

Note

Select Case statements do not support ranges of values; they also do not support use of the greater than (>) or less than (<) signs.


* To use the Select Case construct in VBScript

  1. Open the Exercise9 Web in FrontPage 98.
  2. Open the Home Page in the FrontPage Editor.
  3. Right-click on the Square button and click Script Wizard .
  4. In the OnClick event of btnSquareIt , enter the following code and click OK :
     Dim Result On Error Resume Next Result = SquareIt(T1.Value) Select Case Result Case 1,2,3 MsgBox "Between 1 and 3" Case 4,5,6 MsgBox "Between 4 and 6" Case 7,8,9 MsgBox "Between 7 and 9" Case Else MsgBox "Result is out of range." End Select MsgBox T1.Value & " squared = " & Result 
  5. Save and preview your work with Internet Explorer.
  6. When your Web page appears in Internet Explorer, enter the number 2 in the textbox control, then click Square .
  7. Enter the number 10 in the textbox and then click Square .

    Notice the response for entering a number between one and three. Entering any other number will cause the code under the Case Else statement to execute.

  8. Close Internet Explorer and FrontPage 98.


Microsoft Windows Architecture Training
Microsoft Windows Architecture for Developers Training Kit
ISBN: B00007FY9D
EAN: N/A
Year: 1998
Pages: 324

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net