WIDTH=436>Not supported. Object ManipulationThe CreateObject, GetObject, and TypeOf functions are not supported. OperatorsThe Like operator is not supported. StringsFixed-length strings and the LSet, RSet, Mid, and StrConv functions are not supported. Using ObjectsThe TypeName keyword is not supported. VariablesPublic and Private variables do not seem to be supported. There is conflicting information as of September, 1996. In addition, Static variables are not supported.


Chapter 28 -- VBScript Reference

Chapter 28

VBScript Reference


VBScript syntax and commands are divided into several categories depending on their use and function.

Objects are the building blocks of VBScript. They are used to return and modify the status of forms, pages, the browser, and programmer-defined variables. An easy way to think about an object is as a noun. Cat, car, house, computer, and form are all nouns and could all be represented as an object.

You use properties to differentiate between objects of the same class-for example, all objects that are a cat. Properties are adjectives and refer to items that might make the object different from other objects. In the cat example, this could be weight, color, breed, disposition, and current activity.

You use methods to pass messages to the object and sometimes to change its properties. For example, one method could be used to change the cat's current activity from eating to sleeping, whereas another could be used to change its weight from heavy to really heavy.

The following is a list of the objects, properties, and methods used in VBScript.

+ (Addition)

Syntax: result = operand1 + operand2
Type: Arithmetic Operator
Synopsis: Adds two operands together
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.
See Also: Operators, Subtraction

/ (Division)

Syntax: result = operand1 / operand2
Type: Arithmetic Operator
Synopsis: Divides operand1 by operand2
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero. And, of course, division by zero results in a run-time error.
See Also: On Error, Operators

= (Equality)

Syntax: operand1 = operand2
Type: Comparison Operator
Synopsis: Returns True if operand1 is equal to operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

The equality operator is frequently used in conditional expression for If, Do, and For statements.

Example:

' In this If statement, the equality operator
' is used in the conditional expression.
if intNumPages = 15 Then
Alert "Ok"
End If

' In the third assignment statement below, the
' equality operator is used to give a value of
' False to intTest.
intA = 10
intB = 5
intTest = (intA = intB) ' intTest equals False.

See Also: Operators

^ (Exponentiation)

Syntax: result = operand1 ^ operand2
Type: Arithmetic Operator
Synopsis: Raises operand1 to the power of operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.
See Also: Operators

> (Greater Than)

Syntax: operand1 > operand2
Type: Comparison Operator
Synopsis: Returns True if operand1 is greater than operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

The greater than operator is frequently used in conditional expression for If, Do, and For statements.

Example:

' In this If statement, the greater than operator
' is used in the conditional expression.
if intNumPages > 15 Then
Alert "Ok"
End If

' In the third assignment statement below, the
' greater than operator is used to give a value of
' True to intTest.
intA = 10
intB = 5
intTest = (intA > intB)

See Also: Operators

>= (Greater Than Or Equal To)

Syntax: operand1 >= operand2
Type: Comparison Operator
Synopsis: Returns True if operand1 is greater than or equal to operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

The greater than or equal to operator is frequently used in conditional expression for If, Do, and For statements.

Example:

' In this If statement, the >= operator
' is used in the conditional expression.
if intNumPages >= 15 Then
Alert "Ok"
End If

' In the third assignment statement below, the
' >= operator is used to give a value of
' True to intTest.
intA = 10
intB = 5
intTest = (intA >= intB)

See Also: Operators

<> (Inequality)

Syntax: operand1 <> operand2
Type: Comparison Operator
Synopsis: Returns True if operand1 does not equal operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

The inequality operator is frequently used in conditional expression for If, Do, and For statements.

Example:

' In this If statement, the inequality operator
' is used in the conditional expression.
if intNumPages <> 15 Then
Alert "Ok"
End If

' In the third assignment statement below, the
' inequality operator is used to give a value of
' True to intTest.
intA = 10
intB = 5
intTest = (intA <> intB)

See Also: Operators

\ (Integer Division)

Syntax: result = operand1 \ operand2
Type: Arithmetic Operator
Synopsis: Divides one number by another and rounds the result to the nearest whole number.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero. And, of course, division by zero results in a run-time error.
See Also: On Error, Operators

< (Less Than)

Syntax: operand1 < operand2
Type: Comparison Operator
Synopsis: Returns True if operand1 is less than operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

The less than operator is frequently used in conditional expression for If, Do, and For statements.

Example:

' In this If statement, the less than operator
' is used in the conditional expression.
if intNumPages < 15 Then
Alert "Ok"
End If

' In the third assignment statement below, the
' less than operator is used to give a value of
' False to intTest.
intA = 10
intB = 5
intTest = (intA < intB)

See Also: Operators

<= (Less Than Or Equal To)

Syntax: operand1 < operand2
Type: Comparison Operator
Synopsis: Returns True if operand1 is less than or equal to operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

The less than or equal to operator is frequently used in conditional expression for If, Do, and For statements.

Example:

' In this If statement, the <= operator
' is used in the conditional expression.
if intNumPages <= 15 Then
Alert "Ok"
End If

' In the third assignment statement below, the
' <= operator is used to give a value of
' False to intTest.
intA = 10
intB = 5
intTest = (intA <= intB)

See Also: Operators

* (Multiplication)

Syntax: result = operand1 * operand2
Type: Arithmetic Operator
Synopsis: Multiplies one number by another.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.
See Also: Operators

- (Negation)

Syntax: - operand
Type: Arithmetic Operator
Synopsis: Negates the value of operand.

Example:

intA = 10 ' intA equals positive 10.
intB = -10 ' intB equals negative 10.

See Also: Operators

- (Subtraction)

Syntax: result = operand1 - operand2
Type: Arithmetic Operator
Synopsis: Subtracts operand2 from operand1.
Description: If one of the operands contain the Null value, then the result is Null. If one of the operands contain the Empty value, it is treated as if it were zero.
See Also: Operators

& (String Concatenation)

Syntax: result = string1 & string2
Type: String Concatenation Operator
Synopsis: Appends string2 to string1.
Description: Although you can also use the + operator to concatenate two character strings, you should use the & operator for concatenation instead. The & operator eliminates ambiguity and provides self-documenting code.
See Also: Operators

Abs

Syntax: Abs(number)
Type: Intrinsic Conversion and Math Function
Synopsis: Returns the absolute value of number.

Example:

intTemp = abs(-2) ' intTemp equals 2.
intTemp = abs(2) ' intTemp equals 2.

See Also: Atn, Conversion Functions, Cos, Exp, Log, Math Functions, Randomize, Rnd, Sin, Sqr, Tan

Action

Syntax 1: form.Action
Syntax 2: form.Action = string
Type: Property
Synopsis: Gets or sets the address that does the form's action.
Description: The string parameter is usually a URL that represents a CGI script. However, it can also be a script procedure or an e-mail address. If no URL is specified for a form's action, the base URL is used.

Addition (+)

Syntax: result = operand1 + operand2
Type: Arithmetic Operator
Synopsis: Adds two operands together
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.
See Also: Operators, Subtraction

Alert

Syntax: window.alert(string)
Type:Method
Synopsis:Displays a message dialog box.
Description:If window is not specified, then the current window object is used.

Example:

<!-- This document shows how to use the
Alert method.
-->
<HTML>
<HEAD>
<TITLE>VB Script Example Page</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
Alert("This is an Alert message box.")
-->
</SCRIPT>
</HEAD>
<BODY>
<H1>VB Script Example Page</H1>
Did you like the Alert message?<P>
</BODY>
</HTML>

Picture:

Figure 28.1: An Alert message box.

aLinkColor

Syntax 1: document.aLinkColor = rgbValue
Syntax 2:document.aLinkColor = string
Type:Property
Synopsis:Gets or sets document's active link color.
Description:You can set the color by specifying a RGB value in hexadecimal or by specifying a color name. The "Color Names" entry lists all of the color names that you can use.

A link is active when the mouse pointer is positioned over it and the mouse button is pressed and held down.

You can only set this property while the document is being parsed. An OnLoad event handler procedure is a good place to set document properties.

Caution
Internet Explorer does not support this feature. It is part of the browser's object module for compatibility reasons.

Anchor

Type: Object
Synopsis: Represents a hyperlink link in a document.
Description: Table 28.3 lists the sole property of an anchor object. See the "Anchors" entry for more information.

Table 28.1  Properties of an Anchor Object

PropertyPage Number Description
Namep. 882Gets or sets the name of an anchor.

Anchors

Syntax: document.Anchors[index]
Type: Read-Only Property
Synopsis: Returns an array of anchors, or you can specify an index to retrieve a single anchor.
Description: You can find out how many anchors document has by using the sample code in the Example section. Figure 28.2 shows the results of the example HTML document. Notice that the number of links in the document changes as the document is parsed.

Example:

<!-- This document shows how to determine
the number of anchors in a document.
-->
<HTML>
<HEAD>
<TITLE>VB Script Example Page</TITLE>
<SCRIPT language="VBScript">
<!--
Sub dispAnchors
intNumAnchors = Document.Anchors.Length
Document.Open
Document.Write "This document has " &
intNumAnchors &
" anchors.<P>"
Document.Clear
End Sub

dispAnchors
-->
</SCRIPT>
</HEAD>
<BODY LANGUAGE="VBScript">
<H1>VB Script Example Page</H1>
Visit my home page at
<A NAME="Home Page">http://www.planet.net/pmedined</A>
<P>
<SCRIPT language="VBScript">
<!--
dispAnchors
-->
</SCRIPT>
</BODY>

</HTML>

Picture:

Figure 28.2: The number of anchors in a document depends a lot on when the anchors are counted.

And

Syntax: result = operand1 And operand2
Type: Operator
Synopsis: Returns True if both operands are true.
Description: If one operand is True and the second is Null or if both operands are Null then the result is Null. If the operands are numeric then a bit-wise comparison is made.

Example:

intHasCold = blnFever And blnSniffling

See Also: Operators

AppCodeName

Syntax: navigator.AppCodeName
Type:Read-Only Property
Synopsis:The code name of the current application.
Description:This property returns "Mozilla" when using Microsoft Internet Explorer v3.0 (4.70.1158).

Example:

' Display the application code name.
Alert Navigator.AppCodeName

AppName

Syntax: navigator.AppName
Type:Read-Only Property
Synopsis:The name of the current application.
Description:This property returns "Microsoft Internet Explorer" when using Microsoft Internet Explorer v3.0 (4.70.1158).

Example:

' Display the application name.
Alert Navigator.AppName

AppVersion

Syntax: navigator.AppVersion
Type:Read-Only Property
Synopsis:The version number of the current application.
Description:This property returns "2.0 (compatible; MSIE 3.0A; Windows 95)" when using Microsoft Internet Explorer v3.0 (4.70.1158).

Example:

' Display the application version
Alert Navigator.AppVersion

Array Variables

Type: Definition
Description: An array variable can contain a collection or series of values. Array variables can have more than one dimension. For example, you can use a two-dimensional array to hold values generated by the formula: y = .5 + x. Each x, y pair of values is another element in the array. Three-dimensional arrays are also useful when doing mathematics. While VBScript supports up to 60 dimensions, few programmers use more than three or four.

If you don't know in advance how big the array should be, use a dynamic array. Dynamic arrays are created by using empty parentheses. When your script knows the correct size, the ReDim keyword is used to resize the array.

The lower bound of an array variable is always zero. This means that an array will always hold one more element than is declared in the Dim statement. The following example should make this concept clear.

Table 28.2  VBScript Array Functions and Keywords

FunctionDescription
DimDeclares script-level or procedure-level variables.
EraseReinitializes fixed-size arrays and frees memory associated with dynamic arrays.
IsArrayTests a variable to see if it is an array.
LBoundReturns the smallest subscript for a given dimension of an array.
ReDimDeclares or modifies the bounds for dynamic arrays.
UBoundReturns the largest subscript for dimension of an arrayname.

Example:

<SCRIPT LANGUAGE="VBScript">
<!--
' Declare a vector of integer - a one-dimensional
' array.
Dim aryInt_A(20)

' assign a value to the 5th element.
aryInt_A(4) = 23;

' retrieve the eighth element of the array.
lngNumBooks = aryInt_A(7)

' Declare a 66-element two-dimensional array of
' long integers. It will have 11 rows and 6 columns.
Dim aryLng_B(10, 5)

' assign a value to the first element
aryLng_B(0, 0) = 2343412

' Declare a dynamic array.
Dim ary_C()

' Define the bounds of the dynamic array.
ReDim ary_C(10, 10)

-->
</SCRIPT>

See Also: Dim, IsArray, ReDim

Asc

Syntax: Asc(string)
Type: Intrinsic Conversion and String Function
Synopsis: Returns the ANSI code of the first character in string.
Description: If string contains no characters, a run-time error occurs.

Example:

intTemp = Asc("ABCDE") ' intTemp equals 65.

See Also: AscB, AscW, Chr, ChrB, ChrW, Conversion Functions, InStr, InStrB, Len, LenB, Left, LeftB, Lcase, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

AscB

Syntax: AscB(string)
Type: Intrinsic Conversion and String Function
Synopsis: Returns the first byte in string.
Description: AscB should be used when string contains byte data.
See Also: Asc, AscW, Chr, ChrB, ChrW, Conversion Functions, InStr, InStrB, Len, LenB, Left, LeftB, LCase, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

AscW

Syntax: AscW(string)
Type: Intrinsic String Function
Synopsis: Returns the first Unicode character (32-bits) in string.
Description: AscW should be used when string contains Unicode data.
See Also: Asc, AscB, Chr, ChrB, ChrW, Conversion Functions, InStr, InStrB, Len, LenB, Left, LeftB, LCase, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

Atn

Syntax: Atn(number)
Type: Intrinsic Math Function
Synopsis: Returns the arctangent of number.
Description: The number parameter is the ratio of two sides of a right triangle. Atn will return the corresponding angle in radians. The range of the result is -pi/2 to pi/2 radians. You can multiply radians to degrees to multiplying radians by 180/pi.
See Also: Abs, Cos, Exp, Log, Math Functions, Randomize, Rnd, Sin, Sqr, Tan

Back

Syntax: history.Back(number)
Type: Method
Synopsis: Moves backwards in the history list-exactly as if the browser's back button was clicked.

Example:

' Move backwards five times.
History.Back(5)

BgColor

Syntax 1: document.BgColor = rbgValue
Syntax 1:document.BgColor = string
Type:Method - applies to History objects
Synopsis:Gets or sets document's background color.
Description:You can set the color by specifying a RGB value in hexadecimal or by specifying a color name. The "Color Names" entry lists all of the color names that you can use.

You can only set this property while the document is being parsed. An OnLoad event handler procedure is a good place to set document properties.

Example:

' Set the background color to gold.
Document.BgColor = &HFFD700

See Also: FgColor

Blur

Syntax: element.Blue
Type: Method
Synopsis: Clears the focus from element.
Description: This method causes the OnBlur event.

Boolean Variables

Type: Definition
Description: Boolean variables have only two values, True(1) or False(0). If you use the CBool function to convert a variable into the boolean subtype, anything that is not zero will become True.

VBScript functions and Web browser functions sometime handle boolean variables in different ways. The example section highlights these differences. However, in real world usage you rarely display the value of boolean values. They are almost always used to indicate status (did the mail arrive? has the checkbox been selected?).

Example:

blnTemp = True ' using a constant
blnTemp = CByte(1) ' using a conversion function
Alert blnTemp ' displays "-1"
MsgBox blnTemp ' displays "True"

Byte Variables

Type: Definition
Description: Byte variables can have whole number values ranging from 0 to 255, inclusive.

Example:

bytTemp = CBool(234)

Call

Syntax: Call name([argumentlist])
Type: Keyword
Synopsis: Runs a Sub or Function procedure.
Description: In most cases, the Call keyword is optional. However, if you do use it, then you must also surround the procedure parameter's with parentheses. If you don't use Call then you must also omit the surrounding parentheses. Any return value from functions invoked using Call are ignored.

Example:

Call myFunction(parameterOne, parameterTwo)
myFunction parameterOne, parameterTwo

See Also: Function, Procedure, Sub

CBool

Syntax: CBool(expression)
Type: Intrinsic Conversion Function
Synopsis: Converts expression into a Boolean subtype.
Description: If expression is zero, then False is returned, otherwise True is returned. If expression is not numeric, a run-time error will occur.
E>

Example:

blnBigBook = CBool(numPages > 500)

See Also: CByte, CDate, CDbl, CInt, CLng, Conversion Functions, CSng, CStr

CByte

Syntax: CByte(expression)
Type: Intrinsic Conversion Function
Synopsis: Converts expression into a Byte subtype.
Description: If expression can't be converted into a Byte value, a run-time error will occur.
See Also: CBool, CDate, CDbl, CInt, CLng, Conversion Functions, CSng, CStr

CDate

Syntax: CDate(expression)
Type: Intrinsic Conversion Function
Synopsis: Converts expression into a Date subtype.
Description: The IsDate function can determine if conversion is possible for expression. You can specify date and time literals or a variable as expression. When converting a number to a date, the whole number portion is converted to a date. Any fractional part of the number is converted to a time of day, starting at midnight. CDate usually only recognizes date formats that correspond to the locale setting of your system. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings.

Example:

myBirthday = CDate("9-20-96")

See Also: CBool, CByte, CDbl, CInt, CLng, Conversion Functions, CSng, CStr

CDbl

Syntax: CDbl(expression)
Type: Intrinsic Conversion Function
Synopsis: Converts expression into a Double subtype.
See Also: CBool, CByte, CDate, CInt, CLng, Conversion Functions, CSng, CStr

Checked

Syntax 1: element.Checked
Syntax 2:element.Checked = status
Type:Property
Synopsis:Gets or sets the checked state of element.
Description:If you are testing the checked state, a 1 is returned if element is checked, otherwise a 0 is returned. If you are setting the checked state, status can be either 1 or 0.

Chr

Syntax: Chr(charcode)
Type: Intrinsic Conversion Function
Synopsis: Returns the character associated with charcode.
Description: The ANSI standard assigns a number to each alphanumeric character. The numbers from 0 to 31 are associated with various control functions. For example, the tab character is 9 and the carriage return character is a 13.
See Also: Asc, AscB, AscW, ChrB, ChrW, Conversion Functions, InStr, InStrB, Len, LenB, Left, LeftB, LCase, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

ChrB

Syntax: ChrB(charcode)
Type: Intrinsic Conversion Function
Synopsis: Returns the byte associated with charcode.
Description: ChrB is used for strings with byte data.
See Also: Asc, AscB, AscW, Chr, ChrW, Conversion Functions, InStr, InStrB, Len, LenB, Left, LeftB, LCase, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

ChrW

Syntax: ChrW(charcode)
Type: Intrinsic Conversion Function
Synopsis: Returns the Unicode character associated with charcode.
Description: ChrW is used for strings with byte data. Unicode characters are 32-bits wide.
See Also: Asc, AscB, AscW, Chr, ChrB, Conversion Functions, InStr, InStrB, Len, LenB, Left, LeftB, LCase, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

CInt

Syntax: CInt(expression)
Type: Intrinsic Conversion Function
Synopsis: Converts expression into a Integer subtype.
Description: CInt is used when you need to force integer math. If expression lies outside the acceptable range for the Integer subtype, an error occurs. The CInt function will round the value of expression, not truncate it like Fix and Int. Fractional values of .5 and higher cause CInt to round up to the nearest even number.

Example:

a = CInt(0.5) ' a will equal 0
b = CInt(1.5) ' b will equal 2

See Also: CBool, CByte, CDate, CDbl, CLng, Conversion Functions, CSng, CStr

Clear

Syntax 1: document.Clear
Syntax 2: err.Clear
Type: Method
Synopsis: Closes document and updates the display or clears the property settings for err.
Document Object Description: There seems to be some confusion in the Microsoft documenta tion about the necessity of calling the Clear method. Most of the documentation refers solely to the Close method; however, the Close method does not actually close the document; it simply updates the display according to that same documentation. My best advice is to ignore the Clear method and solely use Close. Hopefully, this confusing situation will be rectified shortly by Microsoft.
Error Object The Clear method should be called to clear the Err object when an error has been handled. The Err object is automatically cleared after On Error Resume Next, Exit Sub, and Exit Function statements.

ClearTimeout

Syntax: window.clearTimeout(timerId)
Type:Method - applies to Window objects
Synopsis:Clears a timeout timer so that it will not go off.
Description:If window is not specified, the current window object is used.

Example:

' Setup a time so that the Send button is clicked in
' five seconds.
clickTimer = setTimeout ("btnSend_OnClick", 5000, "VBScript")

' Clear the timer to avoid automatically clicking
' the Send button.
clearTimer(clickTimer)

See Also: setTimeout

Click

Syntax: element.Click
Type: Method
Synopsis: Emulates the user clicking element.
Description: This method causes an OnClick event.

CLng

Syntax: CLng(expression)
Type: Intrinsic Conversion Function
Synopsis: Converts expression into a Long subtype.
Description: CLng is used when you need to force integer math. The CLng function will round the value of expression, not truncate it like Fix and Int. Fractional values of .5 and higher cause CLng to round up to the nearest even number.

Example:

a = CLng(0.5) ' a will equal 0
b = CLng(1.5) ' b will equal 2

See Also: CBool, CByte, CDate, CDbl, CInt, Conversion Functions, CSng, CStr

Close

Syntax 1: document.Close
Syntax 2:window.Close
Type:Method
Synopsis:Closes document and updates the display or Closes window.
Description:If window is not specified, then the current window object is used. This means that if you simply see a Close method without an attached object, it always means that a window is being closed.

Color Names

Type: Definition
Description: Table 28.3 lists all of the color names that you can use in VB-Script. While you normally specify the RGB value as one six-digit hexadecimal number, the table displays the numbers as separate red, green, and blue two-digit numbers to make understanding the numbers easier.

Table 28.3  VBScript's Color Names

ColorRedGreen Blue

Cookie

Syntax 1: result = document.Cookie
Syntax 2: document.Cookie = string
Type: Read-Only Property
Synopsis: Gets or sets document's cookie.
Description: Cookies are pieces of information that can be associated with document. Setting a cookie overrides any cookie that was previously associated with document.

Confirm

Syntax: result = window.Confirm(string)
Type:Method - applies to Window objects
Synopsis:Displays a message box with OK and Cancel buttons.
Description:If window is not specified, then the current window object is used.
Return Value:Returns True if the OK button was clicked, False otherwise.

Example:

<!-- This document shows how to use the
Confirm method.
-->
<HTML>
<HEAD>
<TITLE>VB Script Example Page</TITLE>
</HEAD>
<BODY>
<H1>VB Script Example Page</H1>
<SCRIPT language="VBScript">
<!--
If Confirm("Click OK to take a survery.") Then
document.open
document.write "Here is the survey<P>"
Else
document.write "Thanks, anyway.<P>"
End If
document.close
-->
</SCRIPT>
</BODY>
</HTML>

Picture:

Figure 28.3: Another Alert message box.

Constants

Type: Definition
Description: VBScript has five built-in constants as shown in Table 28.4. You might notice that the descriptions of True and False do not mention an actual value. This is because their value is irrelevant-just the fact that they are opposites is important.

Table 28.4  VBScript's Constants

ConstantDescription
EmptyIndicates that a variable has not been initialized.
FalseThe opposite of True.
NothingIndicates that a reference does not refer to anything.
NullIndicates that a variable has no valid data.
TrueThe opposite of False.

Conversion Functions

Type: Definition
Description: VBScript has quite a few intrinsic functions designed to convert from one data type to another, from one base to another, or simply from one format to another. Table 28.5 lists the conversion functions available in VBScript.

Table 28.5  VBScript Conversion Functions

FunctionDescription
AbsReturns the absolute value of a number.
AscReturns the ANSI code of the first character in a string.
AscBReturns the first byte in a string.
AscWReturns the first Unicode character (32-bits) in a string.
CBoolConverts a value into a Boolean subtype.
CByteConverts a value into a Byte subtype.
CDate Converts a value into a Date subtype.
CDbl Converts a value into a Double subtype.
ChrReturns the character associated with an ASCI code.
ChrBReturns the byte associated with a character code.
ChrWReturns the Unicode character associated with a character code.
CInt Converts a value into a Integer subtype.
CLng Converts a value into a Long subtype.
CSng Converts a value into a Single subtype.
CStr Converts a value into a String subtype.
DateSerialReturns a string representing the year, month, and year parameters.
DateValue Returns a Date value representing its parameter.
Fix Returns the integer portion of a number.
Hex Converts the value of a string into hexadecimal.
Int Returns the integer half of a number.
Oct Converts the value of a string into hexadecimal.
Sgn Returns 1, -1, or 0 depending on the sign of the parameter.
TimeSerial Returns a Date variable that represents the hour, minute, and second parameters.
TimeValue Returns a Date value representing its parameter.

Cos

Syntax: Cos(angle)
Type: Intrinsic Math Function
Synopsis: Returns the cosine of angle.
Description: The cosine is the ratio of the length of a right angle's side adjacent to the angle divided by the length of the hypotenuse. The returned value is in the range -1 to 1.
See Also: Abs, Atn, Exp, Log, Math Functions, Randomize, Rnd, Sin, Sqr, Tan

CSng

Syntax: CSng(expression)
Type: Intrinsic Conversion Function
Synopsis: Converts expression into a Single subtype.
Description: CSng is used when you need to force single-precision math. If expression lies outside the acceptable range for the Single subtype, an error occurs.
See Also: CBool, CByte, Cdate, CDbl, CInt, CLng, Conversion Functions, CStr

CStr

Syntax: CStr(expression)
Type: Intrinsic Conversion Function
Synopsis: Converts expression into a String subtype.
Description: The CStr function converts expression into a string in a manner that depends on the data type of expression. Table 28.6 shows how the conversion is performed.

Table 28.6  Return Values From CStr

Data Type of ExpressionReturn Format
Boolean"True" or "False".
DateThe date expressed using the short-date format of your system.
NullCauses a run-time error.
EmptyA zero-length string ("").
ErrorA string with the word Error followed by the error number.
NumericA string with the number.

See Also: CBool, CByte, CDate, CDbl, CInt, CLng, Conversion Functions, Csng

Date

Syntax: Date
Type: Intrinsic Date/Time Function
Synopsis: Returns the current system date.

Example:

Alert Date

Picture:

Figure 28.4 : This is what the output from the Date function looks like.

See Also: DateSerial, DateValue, Date/Time Functions, Day, Hour, Minute, Month, Now, Second, Time, TimeSerial, TimeValue, Weekday, Year

Date Variables

Type: Definition
Description: Date variables can range from January 1, 100 to December 31, 9999. Internally, the number one represents the date 1/1/100. Each whole number represents a day and the decimal number represents the time. Negative numbers count back from December 30, 1899 and positive numbers count forward from that date. Decimal values of .0 represent midnight and .5 represents noon.

Literal dates are created by delimiting the date with the # character as shown in the example section below.

Example:

dtmFirstDay = CDate(1.234) ' equals 12/31/1899 5:36:58AM
dtmFirstDay = CDate(1) ' equals 12/31/1899
dblFirstday = CDbl(dtmFirstDay) ' equals 1
dtmBirthday = #09-20-96# ' equals 9/20/1996

Date/Time Functions

Type: Definition
Description: VBScript has many intrinsic functions that work with date and time values. Table 28.7 lists the date/time functions available in VBScript.

Table 28.7  VBScript Date/Time Functions

FunctionDescription
DateReturns the current system date.
DateSerialReturns a string representing the year, month, and year parameters.
DateValue Returns a Date value representing its parameter.
DayReturns the day of the month of its parameter.
HourReturns the hour of the day of its parameter.
MinuteReturns the minute value of its parameter.
MonthReturns the month value of its parameter.
NowReturns the current date and time as a Date value.
SecondReturns the seconds value of its parameter.
TimeReturns the current system time as a Date value.
TimeSerial Returns a Date value representing its parameters.
TimeValue Returns a Date value representing its parameter.
WeekdayReturns the day of the week of its parameter.
YearReturns the year of its parameter.

DateSerial

Syntax: DateSerial(year, month, day)
Type: Intrinsic Conversion and Date/Time Function
Synopsis: Returns a string representing the year, month, and year parameters.
Description: The year parameter can range from 100 to 9999-the values of 0 to 99 are interpreted as the years 1900 to 1999. The month parameter can range from 1-12. And day can range from 1-31. You can pass expressions instead of literals to perform some basic date arithmetic. The example shows how to subtract two from a given month. Parameters that are too large to fit into the normal range will carry over into the next larger unit. For instance, a day parameter of 34 will increment the month parameter. If one of the parameters falls outside the range -32,768 to 32,767, or if the date specified by the three arguments falls outside the acceptable range of dates, an error occurs.

Example:

intMonth = 6
Alert DateSerial(1996, intMonth - 2, 12)

Picture:

Figure 28.5 : This is what the output from the DateSerial function looks like.

See Also: Date, DateValue, Date/Time Functions, Day, Hour, Minute, Month, Now, Second, Time, TimeSerial, TimeValue, Weekday, Year

DateValue

Syntax: DateValue(date)
Type: Intrinsic Date/Time Function
Synopsis: Returns a Date value representing date.
Description: The date parameter is a literal string or a variable that holds a date string. However, date can also be any expression that represents a date value. Time information in date is ignored, but incorrect time will cause an error. DateValue can recognize the abbreviated forms of each month name (Jan, Feb, and so on). The current year of your computer's system date will be used if date does not specify a year.

Example:

Alert DateValue("April 28, 1995")

Picture:

Figure 28.6: This is what the output from the DateValue function looks like.

See Also: Date, DateSerial, Date/Time Functions, Day, Hour, Minute, Month, Now, Second, Time, TimeSerial, TimeValue, Weekday, Year

Day

Syntax: Day(date)
Type: Intrinsic Date/Time Function
Synopsis: Returns the day of the month of date-which can range from
1 to 31. 
Description: If date contains Null, Null is returned.
See Also: Date, Date/Time Functions, DateSerial, DateValue, Hour, Minute, Month, Now, Second, Time, TimeSerial, TimeValue, Weekday, Year

DefaultChecked

Syntax 1: element.DefaultChecked
Syntax 2:element.DefaultChecked = status
Type:Property
Synopsis:Gets or sets the default checked state of element.
Description:If you are testing the default checked state, a 1 is returned if element is checked by default, otherwise a 0 is returned. If you are setting the default checked state, status can be either 1 or 0.

DefaultStatus

Syntax 1: window.DefaultStatus
Syntax 2:window.DefaultStatus = string
Type:Property - applies to a Window object
Synopsis:Gets or sets the default status text for the lower left portion of the status bar.

Example:

' set the default status text.
self.defaultStatus = "Ready for Input"

' assign the default status text to a variable
strDefaultText = self.defaultStatus

DefaultValue

Syntax 1: element.DefaultValue
Syntax 2:element.DefaultValue = string
Type:Property
Synopsis:Gets or sets the default value of element.

Description

Syntax 1: Err.Description
Syntax 2: Err.Description = stringExpression
Type: Property
Synopsis: Gets or sets the description of an error.
Description: The Description property holds a brief description of the error that the Err object represents. If Err.Number represents a run-time error and the Description property is not explicitly set, then the default error description will be used.

Example:

Err.Description = "No more items to process."
Err.Number = 2000

Dim

Syntax: Dim varname[([subscripts])][, varname[([subscripts])]]...
Type: Keyword
Synopsis: Declares script-level or procedure-level variables.
Description: The varname parameter indicates the name of the variable being declared. The subscripts parameter, if used, indicates the dimensions of the associated varname parameter. An array variable can have up to 60 dimensions. For example, Dim aryTemp(10, 15) creates an array of 11x16 elements. You only need to specify the upper bounds of each dimension; the lower bound will always be zero. Dynamic arrays can be created using empty parentheses and the ReDim keyword. An error will occur if a variable is re-dimensioned.

All variables are initialized when declared with Dim. Strings are initialized to a zero-length string ("") and number variables are initialized to zero.

Local variables can be created by using Dim inside Sub or Function procedures. Otherwise, all procedures can access all variables-in other words, variables have a script-level scope by default.

Most programmers place all Dim statements at the beginning of a script or procedure where they are easy to find.

Example:

Dim a(10,10,10) ' a is an array with three dimensions.
Dim b(), c() ' b and c are dynamic arrays.

See Also: Array Variables, Erase, IsArray, LBound, ReDim, UBound

Division (/)

Syntax: result = operand1 / operand2
Type: Arithmetic Operator
Synopsis: Divides operand1 by operand2
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero. And, of course, division by zero results in a run-time error.
See Also: On Error, Operators

Do

Syntax 1: Do While condition [statements] Loop
Syntax 2: Do Until condition [statements] Loop
Syntax 3: Do [statements] Loop While condition
Syntax 4: Do [statements] Loop Until condition
Type: Keyword
Synopsis: Repeatedly executes a statement block while a condition is True or until a condition becomes True.
Description: The only difference between the Do While...Loop and the Do Until...Loop is how the conditional expression is tested. The while loop will continue until the condition is false and the until loop will continue until the condition is true. You decide which one to use based on your own program logic.

There are two forms of each Do...Loop statement. The first form tests the conditional expression before executing the statement block and the second checks the conditional statement after the statement block. Again, the choice depends on your program logic. However, the second form implies that the statement block will only be executed at least once-a handy feature to remember when reading and testing information from a data file.

You can use the Exit Do keyword to exit the loop early. You can nest one Do loop inside another.

Example:

<SCRIPT LANGUAGE="VBScript">
<!--
intTemp = 0
Do While intTemp < 5
Alert intTemp
intTemp = intTemp + 1
Loop

intTemp = 0
Do Until intTemp > 5
Alert intTemp
intTemp = intTemp + 1
Loop

intTemp = 0
Do
Alert intTemp
intTemp = intTemp + 1
Loop Until intTemp > 5

intTemp = 0
Do
Alert intTemp
intTemp = intTemp + 1
Loop While intTemp < 5
-->
</SCRIPT>

See Also: Exit Do

Document (Method)

Type: Object
Synopsis: Represents the Document object associated with window.
Description: Document objects are directly analogous to HTML pages. You use the document object to access hypertext links and form elements of the HTML page.

If the page has objects created with the <OBJECT> tag, you can refer directly to them by name instead of indirectly using the document object.

If window is not specified, the Document object of the current window is returned.

Some of a document's properties can only be set in non-event statements-in other words, the properties can only be set when the HTML document is parsed. You can use an OnLoad event handler to set document properties.

Table 28.8  Methods of Document Objects

MethodDescription
ClearCloses the document and updates the document's display.
CloseUpdates the document's display.
OpenOpens a document for output.
WriteWrites a string into a document.
WriteLnWrites a string into a document with a newline at its end.

Table 28.9  Properties of Document Objects

PropertyDescription
aLinkColorGets or sets the color of active links.
AnchorsAn array of a document's anchors.
BgColorGets or sets a document's background color.
CookieGets or sets a document's cookie.
FgColorGets or sets a document's foreground color.
FormsAn array of a document's forms.
LastModifiedThe last modified date of a document.
LinkColorGets or sets the color of hyperlinks.
LinksAn array of a document's hyperlinks.
LocationGets the document's location object.
ReferrerGets the URL of the referring document.
TitleGets the document's title.
vLinkColorGets or sets the color of visited links.

Document (Property)

Syntax: window.Document
Type:Property
Synopsis:Returns the Document object associated with window.
Description:For more information about Document objects, see the "Document (Object)" Entry.

Double Precision Numbers

Type: Definition
Description: Double-precision variables can have over 300 digits-so that can get pretty large.

Example:

3.1415297
31415927e-7
.31415297E1

Element

Type: Object
Synopsis: Represents a control or object on an HTML document.
Description: Information about form elements are accessed through the Elements property of a form object. See the "Elements" entry for more information.

Table 28.10 lists each type of HTML element and the events, methods and properties that you can use with them. ActiveX controls can also be considered form elements, but there are too many of them to describe here. Refer to the documentation that came with the ActiveX controls for more information.

Table 28.10  Element Types

TypeEvents MethodsProperties
ButtonOnClickClick, Reset, Submit Form, Name, Value
CheckboxOnClickClick Checked, DefaultChecked, Form, Name, Value
Hidden   Name, Value
Password Blur, Focus, Select DefaultValue, Form, Name, Value
RadioOnClickClick, Focus Checked, Form, Name, Value
SelectOnBlur, OnChange, OnFocus Blur, FocusLength, Name, Options, SelectedIndex
TextOnBlur, OnChange, OnFocus, OnSelect Blur, Focus, SelectDefaultValue, Form, Name, Value
Textarea OnBlur, OnChange, OnFocus, OnSelect Blur, Focus, SelectDefaultValue, Form, Name, Value

Table 28.11  Events of an Element Object

EventDescription
OnBlurHappens when the element loses the focus.
OnChangeHappens when the element changes.
OnClickHappens when the element is clicked.
OnFocusHappens when the element gets the focus.
OnSelectHappens when the contents of the element are selected.

Table 28.12  Methods of an Element Object

MethodDescription
BlurClears the focus from an element.
ClickFires the OnClick event.
Focus Sets the focus to an element.
SelectSelects the contents of the element.

Table 28.13  Properties of an Element Object

PropertyDescription
CheckedGets or sets the checkbox's checked state.
DefaultCheckedGets or sets the checkbox's default checked state.
DefaultValueGets or sets the element's default value.
FormGets the form object containing the element.
LengthGets the number of options in a selected element.
NameGets or sets the element's name.
OptionsGets the <OPTIONS> tag for a selected element.
SelectedIndexGets the index for the selected option.
ValueGets or sets the element's value.

Elements

Syntax: form.Elements[index]
Type: Property
Synopsis: An array of objects and controls associated with form.
Description: If the form elements are named, you can access them directly by name. Otherwise, use index to specify which element in the array you want.

Example:

' Find out how many element the form called
' myForm has.
intNumElements = Document.myForm.Elements.Length

' Assign the name of the third element to strName
strName = Document.Forms[2].name

Empty

Syntax: Empty
Type: Constant
Synopsis: Indicates that a variable has not been initialized.

Example:

numRecords = Empty

See Also: IsEmpty, IsNull, Null

Encoding

Syntax 1: form.Encoding
Syntax 2: form.Encoding = string
Type: Property
Synopsis: Gets or sets the encoding for a form.
Description: The encoding of a form is its mime type. For example, "text/html."

Caution
In Internet Explorer v3.0, this property has no effect on the operation of the form.

End Function

Type: Keyword
Synopsis: Ends a function definition.
See Also: Function, Procedure

End Sub

Type: Keyword
Synopsis: Ends a subroutine definition.
See Also: Sub, Procedure

Equality (=)

Syntax: operand1 = operand2
Type: Comparison Operator
Synopsis: Returns True if operand1 is equal to operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

The equality operator is frequently used in conditional expression for If, Do, and For statements.

Example:

' In this If statement, the equality operator
' is used in the conditional expression.
if intNumPages = 15 Then
Alert "Ok"
End If

' In the third assignment statement below, the
' equality operator is used to give a value of
' False to intTest.
intA = 10
intB = 5
intTest = (intA = intB) ' intTest equals False.

See Also: Operators

Eqv

Syntax: result = operand1 Eqv operand2
Type: Operator
Synopsis: Returns True when both operands are logically equivalent.
Description: Both operands need to be equal to True or both operands must be False in order for True to be returned.

If the operands are numeric, a bitwise comparson of identically placed bits is performed.

See Also: Operators

Erase

Syntax: Erase array
Type: Intrinsic Array Function
Synopsis: Reinitializes fixed-size arrays and frees memory associated with dynamic arrays.
Description: Each element of a fixed-size array is set to zero if numeric, a zero-length string if string, or the special Nothing value if an object reference. If you need to reuse an erased dynamic array, use ReDim to redeclare the array's dimensions.
See Also: Array Variables, Dim, IsArray, LBound, ReDim, UBound

Err

Syntax 1: Err.property
Syntax 2: Err.method
Type: Object
Synopsis: Holds information about run-time errors.
Properties: Description, Number, Source
Methods: Clear, Raise
Description: The generator an error (the VBScript engine, OLE Objects, or the VBScript script) is responsible for setting the properties of the Err object. The Raise method will generate a run-time error and the Clear method will clear a run-time error.

The Clear method is executed after every On Error Resume Next, Exit Sub, or Exit Function statement.

The Err object is available to all procedures-it has script-level scope.

Table 28.14  Methods of an Err Object

MethodsDescription
ClearClears property settings for an Err object.
RaiseGenerates a run-time error.

Table 28.15  Properties of an Err Object

PropertyDescription
DescriptionGets or sets the description of an error.
NumberGets or sets a numeric value specifying an error.
SourceGets or sets the name of the object or application that originally generated the error.

Events

Type: Definition
Description: The <A>, <BODY>, <FORM>, <INPUT>, and <OBJECT> HTML tags all have events associated with them. You can place VBScript statements directly inside the tags or you can create an event handler procedure. Both methods of responding to events are covered in the "Event Handling" section.

Table 28.16  VB Script Events

EventDescription
OnBlurHappens when a control or object loses focus.
OnChangeHappens when a control or object has changed.
OnClickHappens when a control, object, or hyperlink is clicked.
OnFocusHappens when a control or object gets the focus.
OnLoadHappens when a document is loaded.
OnMouseMoveHappens when the mouse pointer moves while over a link.
OnMouseOverHappens when the mouse pointer moves over a link.
OnSelectHappens when the contents of a control or object are selected.
OnSubmitHappens just before the form's information is sent to the server.
OnUnloadHappens when a document is unloaded.

Event Handling

Type: Definition
Description: Event handlers are special procedures in VBScript that give it much of its power. They allow the programmer to look for specific user behavior in relation to the HTML page, such as clicking a form button or moving the mouse pointer over an anchor.

When an event occurs, the browser looks first in the tag for VBScript statements to handle the event, and then for a procedure named after the form element associated with the event. For example, if a button called myButton is clicked, then VBScript will look for a procedure called myButton_OnClick.

When event handlers are embedded in HTML tags, they are typically used in forms, but some are also used in anchors and links tags. Virtually anything a user can do to interact with a page is covered with the event handlers, from moving the mouse to leaving the current page.

The three ways of creating event handlers are shown in the Example section.

Example 1:

<!--
The event handler in this example is placed inside
the HEAD section of the HTML page. This is a good
idea of other procedures might call it. Or you want
to add comments to your scripts.
-->
<HTML><HEAD>
<TITLE>My Test Page</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub maleGender_OnClick
MsgBox "Thanks for making a selection."
End Sub
-->
</SCRIPT></HEAD>
<BODY><H1>My Test Page></H1>
<FORM>
<INPUT NAME="maleGender" TYPE="button" VALUE="Male">
</FORM></BODY></HTML>

Example 2:

<!--
In this example, the event handler is placed inside
the form element definition surrounded by single
quotes. Placing an event handler inside the form
element should only be done if the hander is very
small. Otherwise, your HTML page becomes cluttered.
-->
<INPUT NAME="maleGender" TYPE="button" VALUE="Male"
OnClick='MsgBox "Thanks for making a selection."'
LANGUAGE="VBScript">

Example 3:

<!--
This example defines the VBScript statements that
get executed when a specific event happens for a
specific control. The syntax used in this example
can be used with any named form element or any
elements defined by the OBJECT tag. Notice that
the Sub keyword is not needed.
-->
<SCRIPT LANGUAGE="VBScript" EVENT="OnClick" FOR="maleGender">
<!--
MsgBox "Thanks for making a selection."
-->
</SCRIPT>

Exit

Syntax: Exit
Exit Do
Exit For
Exit Function
Exit Sub
Type: Keyword
Synopsis: Exits a block of statements or ends the script.
Description: Exit statements are usually used to alter the flow of program logic in special situations. For example, if the program is inside a loop and the user chooses to cancel the current operation, the Exit Do statement might be used to end the loop.

The Exit Do statement is used to stop all four types of Do...Loop statements.

Each type of Exit statement must be used in the appropriate context. For example, an Exit For statement can't be used to exit from a Do loop.

When an Exit statement is encountered, control is transferred to the statement immediately following the end of the statement block.

Exit Do and Exit For statements are usually combined with an If statement to conditionally exit a statement block. For example, a For loop that counts from 10 to 1,000 might need to be terminated if the user pressed the Esc key.

Example:

<SCRIPT LANGUAGE="VBScript">
<!--
' Exit Do
number = 0
Do While number < 100
Print number
If alert = True Then Exit Do
number = number + 1
Loop

' Exit For
For index = 1 to 10
Print index
If alert = True Then Exit For
Next

-->
</SCRIPT>

See Also: Do...Loops, For...Next Loops, Function, Sub

Exp

Syntax: Exp(number)
Type: Intrinsic Math Function
Synopsis: Returns e (the base of natural logarithms) raised to a power.
Description: If number is greater than roughly 709.782, then an error occurs. The constant e is approximately 2.718282. The Exp function is sometimes called the antologarithm because it complements the Log function.
See Also: Abs, Atn, Cos, Log, Math Functions, Randomize, Rnd, Sin, Sqr, Tan

Exponentiation (^)

Syntax: result = operand1 ^ operand2
Type: Arithmetic Operator
Synopsis: Raises operand1 to the power of operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.
See Also: Operators

FgColor

Syntax 1: document.FgColor = rbgValue
Syntax 2:document.FgColor = string
Type:Property
Synopsis:Gets or sets document's foreground color.
Description:You can set the color by specifying a RGB value in hexadecimal or by specifying a color name. The "Color Names" entry lists all of the color names that you can use.

You can only set this property while the document is being parsed. An OnLoad event handler procedure is a good place to set document properties.

Example:

' Set the foreground color to gold.
Document.FgColor = &HFFD700

See Also: BgColor

Fix

Syntax: Fix(number)
Type: Intrinsic Conversion and Math Function
Synopsis: Returns the integer portion of number.
Description: If number is negative, Fix returns the first negative number greater than or equal to number. Fix(number) is the same as Sgn(number) * Int(Abs(number)).

Example:

a = Fix(-3.37) ' a equals -3.

See Also: CInt, Conversion Functions, Int, Math Functions

Focus

Syntax: element.Focus
Type: Method
Synopsis: Sets the focus to element.
Description: This method causes the OnFocus event.

For

Syntax: For loopVariable = start to end [STEP step]
[statements]
Next
Type: Keyword
Synopsis: Repeatedly executes statements for a specific number of times.
Description: For...Next loops are used to execute a code block a specific number of times. A loop variable is specified for each For...Next statement. The loop variable is initialized to the starting value before the code block is executed. After the execution of the code block, the Step value (step) is added to loop variable. If no step is specified, the loop variable is incremented by one.

When For loops are nested, each loop needs to have a unique variable name. See the Example section for a demonstration of nested For loops.

Example:

' Count forwards from one to five.
For index = 1 to 5
Alert index
Next

' Count backwards from five to one.
For index = 5 to 1 Step -1
Alert index
Next

' Use nested for loop to find row, column pairs.
For row = 0 to 2
For col = 0 to 2
Alert "[" & row & "," & col & "]"
Next
Next

See Also: Do...Loop, Exit

Form

Type: Object
Synopsis: Represents an HTML form.
Description: Most HTML form elements have a Form property that references the form containing the element. So if you need to find out which method of data transfer the form that contains the btnYield button uses, then use btnYield.Form.Method.

You can access each element of a form through the form array that is part of the document object. The forms can be accessed by name or by array index. Refer to the Example section to see how this is done.

Note
I believe that accessing forms by form name leads to self-documenting and more robust scripts. Forms are named by using the NAME attribute of the <FORM> HTML tag. By using the form name in a script, you gain the ability to rearrange the HTML forms (move one on top of another or to the end of the document, perhaps) without needing to recalculate the form's index.

If the script tag is defined inside the form tag, then you don't need to specify the document part of the object specification.

Table 28.17  Events of a Form Object

EventDescription
OnSubmitHappens just before the form data is sent to the server.

Table 28.18  Methods of a Form Object

MethodDescription
SubmitSends the form data to the server.

Table 28.19  Properties of a Form Object

PropertyDescription
ActionGets or sets the address that does the form's action.
ElementsAn array of form objects and controls.
EncodingGets or sets the encoding for the form.
MethodSpecifies how data is sent to the server (either GET or POST)
TargetSets the name of the window where the form should be displayed.

Example:

<!-- This document shows that the document and
form names do not need to be specified if
the script is defined inside the form.
-->
<HTML>
<HEAD>
<TITLE>VB Script Example Page</TITLE>
</HEAD>
<BODY>
<H1>VB Script Example Page</H1>
<FORM NAME="myForm">
<INPUT NAME=btnLaugh TYPE=button VALUE="Want a laugh?">
<script language="VBScript" for="btnLaugh" event="OnClick">
btnLaugh.value="HA-HA!"
</script>
</FORM>
</BODY>
</HTML>

Forms

Syntax: document.Forms[index]
Type:Property
Synopsis:An array of document's forms.
Description:See the "Form" entry for more information.

Forward

Syntax: history.Forward(number)
Type:Method
Synopsis:Moves forwards in the history list-exactly as if the browser's forward button was clicked.

Example:

' Move forward five times.
History.Forward(5)

Frames

Syntax: window.Frames
Type:Property - applies to Window objects
Synopsis:Returns an array of frames contained in window.

Example:

strURL = Parent.Frames[0].Location.Href

Caution
While the Microsoft documentation uses the above example, it generated an error message when I tried it. This problem may be resolved by the time you read this book.

Function

Syntax: Function name [(arglist)]
[statements]
[name = expression]
End Function
Type: Keyword
Synopsis: Creates a user-defined function called name.
Description: Function statements are used to create user-defined functions. Functions differ from subroutines because they do return a value. Simply assign the return value to a variable with the same name as the function.

All functions should be declared towards the beginning of your script in the HEAD section of your HTML page. This ensures that the functions will be available for use by later VBScript statements.

arglist is an optional list of arguments or parameters that the function can use. Functions always return a value and you specify the value to return by assigning it to a variable named identically to name. If you would like the function to assign values to the arguments, use the ByVal keyword inside the parameter list.

Example:

' Define a function with one parameter
Function squareIt(intTemp)
squareIt = intTemp * intTemp
End Function

' Define a function that can modify its
' parameter. This function determines if
' a field's valiue is in the correct range
' and if it is, added the value to an ongoing
' total.
Function IsInValidRange(intField, intMin, intMax, intTotal)
validate = False
If intField >= intMin And intField <= intMax Then
validate = True
intTotal = intTotal + intField
End If
End Function

See Also: Procedure, Sub

Go

Syntax: history.Go(number)
Type:Method
Synopsis:Connects to the URL at position number in the history list.

Example:

' Connect to the first URL in the
' history list.
history.go(1)

Greater Than (>)

Syntax: operand1 > operand2
Type: Comparison Operator
Synopsis: Returns True if operand1 is greater than operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

The greater than operator is frequently used in conditional expression for If, Do, and For statements.

Example:

' In this If statement, the greater than operator
' is used in the conditional expression.
if intNumPages > 15 Then
Alert "Ok"
End If

' In the third assignment statement below, the
' greater than operator is used to give a value of
' True to intTest.
intA = 10
intB = 5
intTest = (intA > intB)

See Also: Operators

Greater Than Or Equal To (>=)

Syntax: operand1 >= operand2
Type: Comparison Operator
Synopsis: Returns True if operand1 is greater than or equal to operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

The greater than or equal to operator is frequently used in conditional expressions for If, Do, and For statements.

Example:

' In this If statement, the >= operator
' is used in the conditional expression.
if intNumPages >= 15 Then
Alert "Ok"
End If

' In the third assignment statement below, the
' >= operator is used to give a value of
' True to intTest.
intA = 10
intB = 5
intTest = (intA >= intB)

See Also: Operators

Hash

Syntax 1: link.Hash
Syntax 2: location.Hash
Syntax 3: location.Hash = string
Type: Property
Synopsis: Gets the hash part of link or location. Sets the hash part of location.
Description: The hash part of an URL starts with a hash mark. For example, in http://www.planet.net/trains.htm#Amtrak, the #Amtrak is the hash part of the URL. If the URL has no hash, then Null is returned.

Hex

Syntax: Hex(number)
Type: Intrinsic Conversion and Math Function
Synopsis: Returns a string that represents the value of number converted into hexadecimal.
Description: Only integer values can be converted. If number is not an integer, it is rounded up to the nearest whole number.
See Also: Conversion Functions, Math Functions

Hierarchies

Type: Definition
Description: In an hierarchy, some relationship exists between all objects. For example, Internet Explorer objects have a structure that reflects the construction of an HTML page. The Window object is the parent of all other Internet Explorer objects. The Location, History, and Document objects are all subordinate to the Window object.

Some objects are contained inside other objects. For example, the form called myForm is an object and it is also the property of a Document object. In addition, the Document object is a property of the Window object. Therefore, the form's full specification is Window.Document.myForm.

History (Object)

Type: Object
Synopsis: Represents the URLs visited by a window.
Description: The History object allows access to the browser's history list. You use the object's method in order to select which URL in the history list that you need to connect with.

Table 28.20  Methods of a History Object

ObjectDescription
BackLike clicking the browser's back button.
ForwardLike clicking the browser's forward button
GoConnects to a specified entry in the history list.

Table 28.21  Properties of a History Object

ObjectDescription
LengthThe number of entries in the list.

History (Property)

Syntax: window.History
Type:Property
Synopsis:Returns the History object of window.
Description:If window is not specified, the history object of the current window is returned.

Host

Syntax 1: link.Host
Syntax 2: location.Host
Syntax 3: location.Host = host
Type: Property
Synopsis: Gets the host for link or location. Sets the host for location.
Description: The host parameter is a string of the form, "hostname:port". This property always returns the empty string ("") for the file: protocol.

Hostname

Syntax 1: link.Hostname
Syntax 2: location.Hostname
Syntax 3: location.Hostname = hostname
Type: Property
Synopsis: Gets the hostname for link or location. Sets the hostname for location.
Description: The hostname parameter can specify either a server name or IP address. This property always returns the empty string ("") for the file: protocol.

Hour

Syntax: Hour(time)
Type: Intrinsic Time/Date Function
Synopsis: Returns the hour of the day (from 0 to 23) in time.
See Also: Date, Date/Time Functions, DateSerial, DateValue, Day, Month, Now, Second, Time, TimeSerial, TimeValue, Weekday, Year

Href

Syntax 1: link.Href
Syntax 2: location.Href
Syntax 3: location.Href = url
Type: Property
Synopsis: Gets the URL for link or location. Sets the URL for location.

If

Syntax 1: If condition Then statement
Syntax 2: If condition Then
[statements]
End If
Syntax 3: If condition Then
[statements]
Else [statements]
End If
Type: Keyword
Synopsis: Optionally Executes statements based on condition.
Description: The Else syntax is optional-only use it when statements need to be executed if condition is false.

Example:

If maritalStatus = "Married" Then
MsgBox "Congradulations!"
moreQuestions = True
Else
MsgBox "Good Luck!"
End If

Imp

Syntax: result = operand1 Imp operand2
Type: Operator
Synopsis: Performs a logical implication on two operands.
Description: The result of the logical implication can be found using Table 28.22 unless the operands are numeric. If the operands are numeric, a bitwise comparson of identically placed bits is performed using Table 28.23.

Table 28.22  The Results of the Imp Operator

Operand1Operand2 Result
TrueTrueTrue
TrueFalseFalse
TrueNullNull
FalseTrueTrue
FalseFalseTrue
FalseNullTrue
NullTrueTrue
NullFalseNull
NullNullNull

Table 28.23  The Results of the Imp Operator for Numeric Operands

Bit in Operand1
Bit in Operand2
Result
0
0
1
0
1
1
1
0
0
1
1
1

See Also: Operators

Inequality (<>)

Syntax: operand1 <> operand2
Type: Comparison Operator
Synopsis: Returns True if operand1 does not equal operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

The inequality operator is frequently used in conditional expression for If, Do, and For statements.

Example:

' In this If statement, the inequality operator
' is used in the conditional expression.
if intNumPages <> 15 Then
Alert "Ok"
End If

' In the third assignment statement below, the
' inequality operator is used to give a value of
' True to intTest.
intA = 10
intB = 5
intTest = (intA <> intB)

See Also: Operators

InputBox

Syntax: InputBox(prompt [, title][, default][, xpos][, ypos][, helpfile, context])
Type: Intrinsic Function
Synopsis: Displays a prompt in a dialog box, waits for the user to enter text or click a button.
Description: The prompt parameter will be displayed in the dialog box for the user to read. The title parameter will be displayed in the title bar of the dialog box. The default parameter will be displayed in the text box where the user entered his input. The xpos and ypos parameters specify, in twips, the horizontal and vertical distance of the dialog box from the top left edge of the screen. If xpos is omitted, the dialog box will be horizontally centered. If ypos is omitted, the dialog box will be placed about one-third of the way down the screen. The helpfile parameter is the name of a help file that will provide context-sensitive help and context is the ID number of the topic that should be displayed when the user presses the F1 key.

InputBox will return the contents of the text box if the user presses ENTER or clicks the OK button. A zero-length string ("") will be returned if the Cancel button is clicked.

Example:

name = InputBox "Please enter your name",
"Name Entry Phase", "John Doe"

InStr

Syntax: InStr([start, ] string1, string2 [, compare])
Type: Intrinsic String Function
Synopsis: Returns the location of string2 in string1.
Description: The start parameter lets you start the search at a position other than beginning of string1. The compare parameter controls the type of search that is performed. Normally, a binary comparison is performed. However, if you use a compare value of 1 then a textual, case-insensitive comparison is performed. If compare is Null, an error occurs. The start parameter must be specified if the compare parameter is specified.

Example:

Alert InStr(10, "This is a fine test", "test")

See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStrB, Len, LenB, Left, LeftB, LCase, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

InStrB

Syntax: InStrB([start, ] string1, string2 [, compare])
Type: Intrinsic String Function
Synopsis: Returns the byte position of string2 in string1.
Description: InStrB is used for binary data contained in strings.
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, Len, LenB, Left, LeftB, LCase, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

Int

Syntax: Int(number)
Type: Intrinsic Conversion and Math Function
Synopsis: Returns the integer half of number.
Description: If number is negative, the first negative number less than or equal to number is returned.

Example:

intA = Int(10.34) ' intA equals 10
intB = Int(-4.4) ' intB equal -5

See Also: CInt, Conversion Functions, Fix, Math Functions

Integer

Type: Definition
Description: Integers are whole numbers such as 1, 16, and 456 and can range from -32,768 to 32,767. They can be expressed in decimal (base 10), hexadecimal (base 16), or octal (base 8) form.

Hexadecimal numbers include 0-9 and a-f, and are represented in VBScript by preceding the number with &H. Octal numbers only include 0-7 and are preceded by &O.

For example, decimal 23 is represented in hexadecimal by &H17 and in octal by &O27.

See Also: Hex, Oct, Variables

Integer Division (\)

Syntax: result = operand1 \ operand2
Type: Arithmetic Operator
Synopsis: Divides one number by another and rounds the result to the nearest whole number.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero. And, of course, division by zero results in a run-time error.
See Also: On Error, Operators

Is

Syntax: result = object1 Is object2
Type: Operator
Synopsis: Returns True if object1 and object2 refer to the same object, otherwise False is returned.
Description: The Is operator compares two object reference variables. When assigning object references to variables, you must use the Set keyword as shown in the Example section.

Example:

Set objA = objCar
Set objB = objCar
intTemp = objA Is objB ' intTemp equals True.

See Also: Operators

IsArray

Syntax: IsArray(varname)
Type: Intrinsic Array and Variant Testing Function
Synopsis: Returns True if varname is an array variable, otherwise False is returned.
See Also: Array Variables, Array Functions, Dim, Erase, IsDate, IsEmpty, IsNull, IsNumeric, IsObject, LBound, ReDim, UBound, VarType

IsDate

Syntax: IsDate(expression)
Type: Intrinsic Date/Time and Variant Testing Function
Synopsis: Returns True if expression represents a date, otherwise False is returned.
Description: In Microsoft Windows, the range of valid dates is January 1, 100 A.D. through December 31, 9999 A.D.; the ranges vary among operating systems.
See Also: Date/Time Functions, IsArray, IsEmpty, IsNull, IsNumeric, IsObject, VarType

IsEmpty

Syntax: IsEmpty(expression)
Type: Intrinsic Variant Testing Function
Synopsis: Returns True if expression represents an uninitialized variable or has the Empty value, otherwise False is returned.
Description: If expression contains more than one variable, IsEmpty will always return False.
See Also: Empty, IsArray, IsDate, IsNull, IsNumeric, IsObject, VarType

IsNull

Syntax: IsNull(expression)
Type: Intrinsic Variant Testing Function
Synopsis: Returns True if expression contains no valid data or has the Null value, otherwise False is returned.
Description: If expression contains more than one variable, any Null value will cause IsNull to return True.

Example:

If IsNull(numRecords) Then
Alert "No records were available!"
End If

See Also: IsArray, IsDate, IsEmpty, IsNumeric, IsObject, Null, VarType

IsNumeric

Syntax: IsNumeric(expression)
Type: Intrinsic Variant Testing Function
Synopsis: Returns True if expression contains a number, otherwise False is returned.
Description: If expression contains a date, IsNumeric will return False.

Example:

If IsNumeric(Document.myForm.myText.Value) Then
     sgBox "The value is numeric"
Else
     sgBox "Please enter a number!"
End If

See Also: IsArray, IsDate, IsEmpty, IsNull, IsObject, VarType

IsObject

Syntax: IsObject(expression)
Type: Intrinsic Variant Testing Function
Synopsis: Returns True if expression references an object, otherwise False is returned.
See Also: IsArray, IsDate, IsEmpty, IsNull, IsNumeric, VarType

LastModified

Syntax: document.LastModified
Type: Read-Only Property
Synopsis: Returns a string containing the date that document was last modified.

LBound

Syntax: LBound(arrayname [, dimension])
Type: Intrinsic Array Function
Synopsis: Returns the smallest available subscript for dimension.
Description: The dimension parameter will default to one if not specified. The default lower bound for any dimension is always zero.

Use the LBound function in conjunction with the UBound function to determine an array's size.

See Also: Array Variables, Dim, Erase, IsArray, ReDim, UBound

LCase

Syntax: Lcase(string)
Type: Intrinsic String Function
Synopsis: Returns a copy of string with all characters converted to lowercase.
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LeftB, Len, LenB, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

Left

Syntax: Left(string, length)
Type: Intrinsic String Function
Synopsis: Returns a copy of the first length characters of string.
Description: If length is greater than string's length then the entire string is returned.

Example:

' removes the last character from strA
strB = Left(strA, Len(strA) - 1)

See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LCase, LeftB, Len, LenB, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

LeftB

Syntax: LeftB(string, length)
Type: Intrinsic String Function
Synopsis: Returns a copy of the first length bytes of string.
Description: LeftB should be used with binary data. If length is greater than string's length then the entire string is returned.

Example:

' removes the last byte from strA
strB = Left(strA, Len(strA) - 1)

See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LCase, Left, Len, LenB, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

Len

Syntax: Len(string | varname)
Type: Intrinsic String Function
Synopsis: Returns the number of characters in string or the number of bytes it takes to store varname's value.
Description: If string or varname is Null, then Null is returned.

Example:

strA = "12345"
intB = Len(strA) ' intB equals 5

See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LCase, Left, LeftB, LenB, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

LenB

Syntax: LenB(expression)
Type: Intrinsic String Function
Synopsis: Returns the length of expression in bytes.
Description: LenB should be used with binary data.
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LCase, Left, LeftB, Len, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

Length

Syntax 1: element.Length
Syntax 2: history.Length
Type: Property
Synopsis: Gets the number of options in a Select element or gets the number of entries in the browser's history list.
Limitation: The Length property of History objects always returns zero in Internet Explorer v3.0.

Less Than (<)

Syntax: operand1 < operand2
Type: Comparison Operator
Synopsis: Returns True if operand1 is less than operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

The less than operator is frequently used in a conditional expression for If, Do, and For statements.

Example:

' In this If statement, the less than operator
' is used in the conditional expression.
if intNumPages < 15 Then
Alert "Ok"
End If

' In the third assignment statement below, the
' less than operator is used to give a value of
' False to intTest.
intA = 10
intB = 5
intTest = (intA < intB)

See Also: Operators

Less Than Or Equal To (<=)

Syntax: operand1 < operand2
Type: Comparison Operator
Synopsis: Returns True if operand1 is less than or equal to operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

The less than or equal to operator is frequently used in a conditional expression for If, Do, and For statements.

Example:

' In this If statement, the <= operator
' is used in the conditional expression.
if intNumPages <= 15 Then
Alert "Ok"
End If

' In the third assignment statement below, the
' <= operator is used to give a value of
' False to intTest.
intA = 10
intB = 5
intTest = (intA <= intB)

See Also: Operators

Link

Type: Object
Synopsis: Represents a hyperlink.
Description: Link objects are accessed using the Links property of a document object. See the "Links" entry for additional information.

Table 28.24  Events of a Link Object

EventDescription
OnClickHappens when a hyperlink is clicked.
OnMouseMoveHappens when the mouse pointer moves and it is over a hyperlink.
OnMouseOverHappens when the mouse pointer moves over a hyperlink.

Table 28.25  Properties of a Link Object

PropertyDescription
HashGets or sets the hash part of the URL.
HrefGets or sets the whole URL.
HostGets or sets the host and port part of the URL.
HostnameGets or sets the hostname part of the URL.
PathnameGets or sets the pathname part of the URL.
PortGets or sets the port part of the URL.
ProtocolGets or sets the protocol part of the URL.
SearchGets or sets the search part of the URL.
TargetGets the target of the hyperlink.

See Also: Links

LinkColor

Syntax 1: document.LinkColor = rgbValue
Syntax 2:document.LinkColor = string
Type:Property
Synopsis:Gets or sets document's hyperlink color.
Description:You can set the color by specifying a RGB value in hexadecimal or by specifying a color name. The "Color Names" entry lists all of the color names that you can use.

You can only set this property while the document is being parsed. An OnLoad event handler procedure is a good place to set document properties.

Links

Syntax: document.Links[index]
Type: Read-Only Property
Synopsis: Returns an array of links, or you can specify an index to retrieve a single link.
Description: You can find out how many links document has by using the sample code in the example section. Figure 28.7 shows the results of the example HTML document. Notice that the number of links in the document changes as the document is parsed.

Example:

<!-- This document shows how to determine
the number of links in a document.
-->
<HTML>
<HEAD>
<TITLE>VB Script Example Page</TITLE>
<SCRIPT language="VBScript">
<!--
Sub dispLinks
intNumLinks = Document.Anchors.Length
Document.Open
Document.Write "This document has " &
intNumLinks &
" links.<P>"
Document.Clear
End Sub

dispLinks
-->
</SCRIPT>
</HEAD>
<BODY LANGUAGE="VBScript">
<H1>VB Script Example Page</H1>
Visit my home page at
<A HREF="http://www.planet.net/pmedined">
http://www.planet.net/pmedined
</A>
<P>
<SCRIPT language="VBScript">
<!--
dispLinks
-->
</SCRIPT>
</BODY>
</HTML>

Picture:

Figure 28.7: The number of links in a document depends a lot on when the links are counted.

Literal Values

Type: Definition
Description: A literal is a value that is represented "as is" in your source code. VBScript uses several types of literals: boolean, date, floating-point (both single and double precision), integer, and string. Table 28.26 shows an example of each data type. In addition, each data type has its own entry in this book.

Table 28.26  VBScript Literal Values

Data TypeValue
BooleanTrue or False
Date"01/23/1996" "Jan 23, 1996"
Single Precision12.34
Double Precision34.67
Integer45
String"Hello, World"

Location (Object)

Type: Object
Synopsis: Represents the URL of a document or window.
Description: The Location object does not have any events or methods. Table 28.27 lists the Location object's properties.

Table 28.27  Properties of a Location Object

PropertyDescription
HashGets or sets the hash part of the URL.
HrefGets or sets the whole URL.
HostGets or sets the host and port part of the URL.
HostnameGets or sets the hostname part of the URL.
PathnameGets or sets the pathname part of the URL.
PortGets or sets the port part of the URL.
ProtocolGets or sets the protocol part of the URL.
SearchGets or sets the search part of the URL.

Location (Property)

Syntax 1: document.Location
Syntax 2:window.Location
Type:Read-Only Property
Synopsis:Returns the Location object for document, or window.
Description:If window is not specified, then Location object of the current window is returned.

If you need the location object for a document, you must specify the document object (most of the time, you use document.Location).

See the "Location (Object)" Entry for more information.

Log

Syntax: Log(number)
Type: Intrinsic Math Function
Synopsis: Returns the natural logarithm of number.
Description: The natural logarithm is the logarithm to the base e. The constant e is approximately 2.718282.
See Also: Abs, Atn, Cos, Exp, Math Functions, Randomize, Rnd, Sin, Sqr, Tan

Long Variables

*

Type: Definition
Description: Long variables are whole numbers that can range from -2,147,483,648 to 2,147,483,647.

Example:

lngTemp = 1222333

LTrim

Syntax: LTrim(string)
Type: Intrinsic Math Function
Synopsis: Returns a copy of string without leading spaces.
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LeftB, Len, LenB, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

Math Functions

Type: Definition
Description: VBScript has relatively few math functions and they are listed in Table 28.28.

Table 28.28  VBScript Math Functions

FunctionDescription
AbsReturns the absolute value of a number.
AtnReturns the arctangent of a number.
CosReturns the cosine of an angle.
ExpReturns e raised to a power.
LogReturns the natural logarithm of number.
RandomizeInitializes the random-number generator.
RndReturns a random number.
SinReturns the sine of an angle.
SqrReturns the square root of a number.
TanReturns the tangent of angle.

Method

Syntax 1: form.Method
Syntax 2: form.Method = string
Type: Property
Synopsis: Gets or sets the method for sending form information to the sever.
Description: You can send form information to the server using either the GET or POST method.

Methods

Type: Definition
Description: A method is a function assigned to an object. For example, document.myForm.Submit() will execute the Submit method and send the information from the myForm form to the server.
See Also: Procedures

Mid

Syntax: Mid(string, start [, length ])
Type: Intrinsic String Function
Synopsis: Returns a copy of the part of string beginning at start for length characters.
Description: If string contains Null, then Null is returned. If start is greater than the length of string, then a zero-length string will be returned. If no length parameter is specified then all characters from start to the end of the string are returned.
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LeftB, Len, LenB, LTrim, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

MidB

Syntax: MidB(string, start [, length ])
Type: Intrinsic String Function
Synopsis: Returns a copy of the part of string beginning at start for length bytes.
Description: MidB should be used for binary information.
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LeftB, Len, LenB, LTrim, Mid, Right, RightB, Space, StrComp, String, String Functions, Trim, UCase

Minute

Syntax: Minute(time)
Type: Intrinsic Date/Time Function
Synopsis: Returns the minute value in time-which can range from 0 to 59, inclusive.
See Also: Date, Date/Time Functions, DateSerial, DateValue, Day, Month, Now, Second, Time, TimeSerial, TimeValue, Weekday, Year

Mod (Modulus)

Syntax: result = operand1 Mod operand2
Type: Operator
Synopsis: Returns the remainder of operand1 divided by operand2.
Description: The Modulus operator is a special form of division that only returns the remainder of the operation. If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

Example:

i = 8 Mod 2 ' returns 0
i = 8 Mod 3 ' returns 2

See Also: Operators

Modulus (Mod)

Syntax: result = op1 Mod op2
Type: Operator
Synopsis: Returns the remainder of operand1 divided by operand2
Description: The Modulus operator is a special form of division that only returns the remainder of the operation. If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

Example:

i = 8 Mod 2 ' returns 0
i = 8 Mod 3 ' returns 2

See Also: Operators

Month

Syntax: Month(date)
Type: Intrinsic Date/Time Function
Synopsis: Returns the month value in date-which can range from 1 to 12, inclusive.
See Also: Date, Date/Time Functions, DateSerial, DateValue, Day, Minute, Now, Second, Time, TimeSerial, TimeValue, Weekday, Year

MouseOver

Type: Event
Synopsis: Happens when the user moves the mouse pointer over an object or control.

MsgBox

Syntax: MsgBox(stringt [, buttons][, title][, helpfile, context])
Type: Intrinsic Function
Synopsis: Displays a message in a dialog box and waits for the user to click a button. Returns an value related to the button that was clicked according to Table 28.29.

Table 28.29  Return Values From MsgBox

Value
Description
1
OK button was pressed.
2
Cancel button or the ESC key was pressed.
3
Abort button was pressed.
4
Retry button was pressed.
5
Ignore button was pressed.
6
Yes button was pressed.
7
No button was pressed.

Description: The string parameter is displayed inside the dialog box when it appears. You can display about 1,024 characters depending on the font that is used. Multi-line prompts can be created by separating by adding a carriage return character (Chr(13)) into string where you want the lines to end.

The buttons parameter controls which buttons are displayed in dialog box. It also controls which icon is displayed, the modality, and which button is the default. The default value for buttons is zero, which displays the OK button. Use the following table to determine the value of buttons that you need:

Table 28.30  The buttons Parameter of MsgBox

ValueDescription
Values Affecting the Number and Type of Buttons
0Displays the OK button.
1Displays the OK and Cancel buttons.
2Displays the Abort, Retry, and Ignore buttons.
3Displays the Yes, No, and Cancel buttons.
4.Displays the Yes and No buttons.
5Displays the Retry and Cancel buttons.
Values Affecting the Icon Style
16Displays the Critical Message icon.
32Displays the Warning Query icon.
48Displays the Warning Message icon.
64Displays the Information Message icon.
Values That Set the Default Button
0Makes the first button the default.
256Makes the second button the default.
512Makes the third button the default.
768Makes the fourth button the default.
Values That Set the Modality
0Makes the dialog box application modal - user must respond before work can continue in the current application.
4096Makes the dialog box system modal - user must respond before work can continue in any applications. Use this option with care!

Add together one number from each sub-section of the above table to arrive at the correct value for buttons.

The helpfile and context parameters work together to define what happens if the user presses the F1 key or the question-mark button while the dialog box is active.

Multiplication (*)

Syntax: result = operand1 * operand2
Type: Arithmetic Operator
Synopsis: Multiplies one number by another.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.
See Also: Operators

Name

Syntax 1: anchor.name
Syntax 2:element.name
Syntax 3:element.name = string
Syntax 4:window.name
Type:Read-Only Property
Synopsis:Gets the name of anchor, element or window. Sets the name of element.
Description:If window has no name, then "null" is returned. If window is not specified, the name of the current window is returned.

Example:

' Assign the current window name to strWindowName.
strWindowName = name

Navigate

Syntax: window.Navigate(url)
Type:Method - applies to Window objects
Synopsis:Connects the current window to a new URL.
Description:If window is not specified, then the current window is used.

Example:

' switch the current window to the Microsoft Home Page
Navigate("http://www.microsoft.com")

Navigator (Object)

Type: Object
Synopsis: Represents the browser.
Description: The Navigator object lets you access information about the browser.

Table 28.31  Properties of a History Object

ObjectDescription
AppCodeNameThe code name of the browser.
AppNameThe name of the browser.
AppVersionThe version of the browser.
UserAgentThe user agent name of the browser.

Navigator (Property)

Syntax: window.Navigator
Type:Property
Synopsis:Returns the Navigator object associated with window.
Description:See the "Navigator (Object)" entry for more information.

Negation (-)

Syntax: - operand
Type: Arithmetic Operator
Synopsis: Negates the value of operand.

Example:

intA = 10 ' intA equals positive 10.
intB = -10 ' intB equals negative 10.

See Also: Operators

Not

Syntax: result = Not operand
Type: Operator
Synopsis: Returns the logical opposite of expression.
Description: The Not function returns True if operand is False and False if operand is True. If operand is a variable, it returns a copy of the variable with each bit inverted. If operand is Null, then Null is returned.
See Also: Operators

Not Equals (<>)

Syntax: operand1 <> operand2
Type: Comparison Operator
Synopsis: Returns True if operand1 does not equal operand2.
Description: If either operand has the Null value, then result is Null. Operands that have the Empty value are equivalent to zero.

The inequality operator is frequently used in conditional expression for If, Do, and For statements.

Example:

' In this If statement, the inequality operator
' is used in the conditional expression.
if intNumPages <> 15 Then
Alert "Ok"
End If

' In the third assignment statement below, the
' inequality operator is used to give a value of
' True to intTest.
intA = 10
intB = 5
intTest = (intA <> intB)

See Also: Operators

Now

Syntax: Now
Type: Intrinsic Date/Time Function
Synopsis: Returns the current date and time.
See Also: Date, Date/Time Functions, DateSerial, DateValue, Day, Minute, Month, Second, Time, TimeSerial, TimeValue, Weekday, Year

Null

Syntax: Null
Type: Constant
Synopsis: Indicates that a variable has no valid data.
Description: Typically, Null is assigned to variables to indicate that they have no valid data. For instance, you might assign Null to a variable called numRecords to indicate that a data file could not be opened.

Null is not the same as Empty, which indicates that a variable has not yet been initialized. It is also not the same as a zero-length string, which is sometimes referred to as a null string.

You can't directly test to see if a variable has a Null value because any expression containing Null is itself Null. Therefore, you must use the IsNull function to test for the Null value.

Example:

numRecords = Null

See Also: Empty

Number

Syntax 1: Err.Number
Syntax 2: Err.Number = errornumber
Type: Property
Synopsis: Gets or sets a numeric value specifying an error.
Description: You set Err.Number when returning a user-defined error. Add your error number to the variable vbObjectError when return OLE Automation or ActiveX errors. Normally, you create a list of pseudo-constants that hold error values to avoid re-using numbers.

Example:

' Raise an error.
' Notice that I use my initials as a prefix
' for the pseudo-constants. This should avoid
' naming conflicts with another programmer's
' scripts.
dmErrNoFile = 1000
dmErrNoRecords = 1001
Err.Raise Number:= vbObjectError + dmErrNoFile, Source:= "myClass"

Objects

Type: Definition
Description: An object has properties that are either variables or references to other objects. Functions associated with objects are called the object's methods. You access the properties and methods of an object with a simple notation:

objectName.propertyName
objectName.methodName

All names are case-insensitive. This means that OnClick is the same as onClick, or even ONCLICK.

Table 28.32 lists the predefined objects in VBScript and the page that discusses them:

Table 28.32  Predefined Objects Associated With HTML

ObjectDescription
AnchorRepresents a hyperlink link in a document.
DocumentRepresents the Document object associated with a window.
ElementRepresents a control or object on an HTML document.
FormRepresents an HTML form.
HistoryRepresents the URLs visited by a window.
LinkRepresents an hyperlink.
LocationRepresents the URL of a document or window.
NavigatorRepresents the browser.
WindowRepresents a window in the browser.

Object Variables

Syntax: Definition
Description: Object variables are really pointers (or references) to a block of memory that holds an OLE Automation object. Both ActiveX and Java controls are considered to be OLE Automation objects.
See Also: Objects

Oct

Syntax: Oct(number)
Type: Intrinsic Conversion and Math Function
Synopsis: Returns a string representing the octal value of number.
Description: If number is Null, then Null is returned. If number is Empty then zero is returned. If number is not an integer, then it is rounded to the nearest whole number.
See Also: Conversion Functions, Math Functions

OnBlur

Syntax: element.OnBlur
Type:Event
Synopsis:Happens when element loses the focus.
See Also:Events, Event Handling, OnChange, OnClick, OnFocus, OnLoad, OnMouseMove, OnMouseOver, OnSelect, OnSubmit, OnUnload

OnChange

Syntax: element.OnChange
Type:Event
Synopsis:Happens when element has changed.
See Also:Events, Event Handling, OnBlur, OnClick, OnFocus, OnLoad, OnMouseMove, OnMouseOver, OnSelect, OnSubmit, OnUnload

OnClick

Syntax 1: element.OnClick
Syntax 2:link.OnClick
Type:Event
Synopsis:Happens when the user clicks an element or a hyperlink.
See Also:Events, Event Handling, OnBlur, OnChange, OnFocus, OnLoad, OnMouseMove, OnMouseOver, OnSelect, OnSubmit, OnUnload

OnFocus

Syntax: element.OnFocus
Type:Event
Synopsis:Happens when element gets the focus.
See Also:Events, Event Handling, OnBlur, OnChange, OnClick, OnLoad, OnMouseMove, OnMouseOver, OnSelect, OnSubmit, OnUnload

OnLoad

Syntax: OnLoad = eventHandler
Type:Event
Synopsis:Happens after all of the HTML for a document has been parsed and processed.
Description:An OnLoad event handler function is a good place to put initialization statements. Since the OnLoad event handler is defined inside the HTML <BODY> tag, there can be only one function per HTML document.

Example:

<!-- This document shows how to use the
OnLoad event.
-->
<HTML>
<HEAD>
<TITLE>VB Script Example Page</TITLE>
<SCRIPT language="VBScript">
<!--
Sub loadHandler
Alert "The document has loaded!"
End Sub
-->
</SCRIPT>
</HEAD>
<BODY LANGUAGE="VBScript" OnLoad="loadHandler">
<H1>VB Script Example Page</H1>
</BODY>
</HTML>

See Also: Events, Event Handling, OnBlur, OnChange, OnClick, OnFocus, OnMouseMove, OnMouseOver, OnSelect, OnSubmit, OnUnload

OnMouseMove

Syntax: link.OnMouseMove(shift, button, x, y)
Type:Event
Synopsis:Happens when the mouse pointer moves while over a hyperlink.
Description:The parameters are automatically passed to your event handler routine by the browser. The shift parameter holds the status of the shift key. The button indicates which button on the mouse is pressed, if any. The x and y parameters indicate the position of the mouse pointer in pixels.

The Microsoft documentation indicates that the shift and button parameters are currently set to zero and are, therefore, not accurate.

The Example section shows one way to create an event handler for this event.

Example:

' The following script handles the OnMouseMove
' event for a single hyperlink named lnkMicrosoftHome.

<SCRIPT LANGUAGE="VB Script" FOR="lnkMicrosoftHome"
EVENT="OnMouseMove(shift, button, x, y)">
<!--
' add the event handler statements here.
-->
</SCRIPT>

See Also: Events, Event Handling, OnBlur, OnChange, OnClick, OnFocus, OnLoad, OnMouseOver, OnSelect, OnSubmit, OnUnload

OnMouseOver

Syntax: link.OnMouseOver
Type:Event
Synopsis:Happens when the mouse pointer moves over a hyperlink.
Description:You can attach a script to this event using the HTML <SCRIPT> tag as shown in the example for the OnMouseMove event. Or you can place VBScript statements directly in an <A> tag using OnMouseOver as an attribute. The Example section shows how this is done.

Example:

' The following script handles the OnMouseMove
' event for a single hyperlink named lnkMicrosoftHome.

<SCRIPT LANGUAGE="VB Script" FOR="lnkMicrosoftHome"
EVENT="OnMouseMove(shift, button, x, y)">
<!--
' add the event handler statements here.
-->
</SCRIPT>

See Also: Events, Event Handling, OnBlur, OnChange, OnClick, OnFocus, OnLoad, OnMouseMove, OnSelect, OnSubmit, OnUnload

OnSelect

Syntax: element.OnSelect
Type:Event
Synopsis:Happens when the contents of element are selected.
See Also:Events, Event Handling, OnBlur, OnChange, OnClick, OnFocus, OnLoad, OnMouseMove, OnMouseOver, OnSubmit, OnUnload

OnSubmit

Syntax: form.OnUnload = eventHandler
Type:Event
Synopsis:Happens just before the form's information is sent to the server.
Description:You can use this event to perform information validation and prevent the information from being sent if it is not valid. A validation function must return False to prevent submitting the form. The Example section shows how this can be done.

Example:

' The Return keyword must be used in order for VB Script
' to pay attention to the return value of a validation
' function. If the Return keyword is not used, the return
' value is ignored.
document.myForm.OnSubmit = "return IsValid()"

See Also: Events, Event Handling, OnBlur, OnChange, OnClick, OnFocus, OnLoad, OnMouseMove, OnMouseOver, OnSelect, OnUnload

OnUnload

Syntax: OnUnload = eventHandler
Type:Event
Synopsis:Happens after the document has been unloaded.
Description:You can see the unload event handler in action by loading the HTML document in the example section and then clicking the browser's refresh button.

Example:

<!-- This document shows how to use the
OnUnload event.
-->
<HTML>
<HEAD>
<TITLE>VB Script Example Page</TITLE>
<SCRIPT language="VBScript">
<!--
Sub unloadHandler
Alert "The document has loaded!"
End Sub
-->
</SCRIPT>
</HEAD>
<BODY LANGUAGE="VBScript" OnUnload="unloadHandler">
<H1>VB Script Example Page</H1>
</BODY>
</HTML>

See Also: Events, Event Handling, OnBlur, OnChange, OnClick, OnFocus, OnLoad, OnMouseMove, OnMouseOver, OnSelect, OnSubmit

On Error

Syntax: On Error Resume Next
Type: Keyword
Synopsis: Enables or disables an error-handling routine.
Description: If an On Error statement is not used, all run-time errors are fatal.

The On Error Resume Next statement essentially causes run-time errors to be ignored. However, you can still examine the Err object to see if an error has occurred. You should check the Err object after each procedure call that has a high-probability of generating a run-time error. Each procedure that you write needs it own On Error Resume Next statement in order to trap errors local to that procedure.

See Also: Err

Open

Syntax 1: document.open
Syntax 2:newWindow = Window.Open(url, target, options)
Type:Method
Synopsis:Opens document for output or creates a new browser window.
Document Object escription:The Open method opens document for output. Then Write or WriteLn methods are used to append HTML-based text to the document. After all text has been written, the close or clear method is used to update the browser's window.
Window Object Description:When the new window has been successfully created, the Window object associated with the new window is returned.

While the Microsoft documentation indicates that using "Window" is optional, when it is not specified, a syntax error is created.

The url parameter can be either an absolute or a relative URL.

If target names an existing window, that window will be reused. The target parameter is directly analogous to the TARGET attribute in HTML.

You can turn the following options on or off using either "yes" or "no" in a comma-delimited list: toolbar, location, directories, status, menubar, scrollbars, and resizeable. You can specify the height and width of the new window in pixels. In addition, you can set the location of the top left corner of the window, by setting the top and left options.

Caution
Some problems seems to exist with this method. The results of the example HTML are shown in the picture for this entry. You'll notice that while the parameters to the Open method indicate that the window should not be resizeable, it is. In addition, even though the Open method works, I received an error message that said, " Microsoft VBScript runtime error [Line: 12] Object doesn't support this property or method". Please test very thoroughly when using this method.

Example:

<!-- This document shows how to use the
Confirm method.
-->
<HTML>
<HEAD>
<TITLE>VB Script Example Page</TITLE>
</HEAD>
<BODY>
<H1>VB Script Example Page</H1>
<SCRIPT language="VBScript">
<!--
newWin = window.open("C:/WebSite\root\index.htm",
"", "toolbar=no, menubar=no, resizeable=no")
-->
</SCRIPT>
</BODY>
</HTML>

Picture:

Figure 28.8: Even though the parameters indicate that this window is not resizable, it is.

Opener

Syntax: window.Opener
Type:Read-Only Property - applies to a Window object
Synopsis:Returns the Window object that represents the window that opened the current window.

Operators

Type: Definition
Description: Operators are instructions you give to the computer so that it can perform some task or operation. All operators cause actions to be performed on operands. An operand can be anything that you perform an operation on. In practical terms, any particular operand will be a literal, a variable, or an expression. VBScript operators can be divided into two basic classes: binary and unary. Binary operators need two operands and unary operators need a single operand.

I like to think about operators in the same way I would give instructions to the driver of a car. I might say "turn left" or "turn right." These commands could be considered directional operators in the same way that + and - mathematical operators that say "add this" or "subtract this." If I yell "stop" while the car is moving, on the other hand, it should supersede the other commands. This means that "stop" has precedence over "turn left" and "turn right."

For example, the subtraction operator is a binary operator:

5 - 2

Of course, simply subtracting two numbers together doesn't mean much if you don't store the value somewhere. This is where variables play a role. You can assign values to variables using the assignment operator:

int_Num = 5 - 2

The minus sign can also act as a unary operator when placed in front of a number. For example,

int_Num = -34

Table 28.33 lists all of VBScript's operators. Some of them will be familiar to you from math class-for others, you might need a description. Operators that have their own entry in this book have the page number indicted in the third column.

Table 28.33  VBScript's Operators

OperatorName Description
Arithmetic Operators
+AdditionAdds two operands together.
/DivisionDivides one number by another.
^ExponentiationRaises one number to the power of another.
\Integer divisionDivides one number by another and rounds the result to the nearest whole number.
ModModulusReturns the remainder of a division operation.
*MultiplicationMultiplies one number by another.
-NegationNegates a number.
-SubtractionSubtracts one number from another.
Comparison Operators
=EqualityReturns True if one number equals another.
>Greater thanReturns True if one number is greater than another.
>=Greater than or Returns True if one number is greater than equal to or equal to another.
<>InequalityReturns True if two numbers are not equal.
<Less thanReturns True if one number is greater than another.
<=Less than orReturns True if one number is less than equal to or equal to another
IsObjectReturns True if two object references equivalence refer to the same object.
Logical Operators
AndConjunctionReturns True if its two operands are true.
EqvEquivalenceReturns True if its two operands are logically equivalent.
ImpImplicationPerforms a logical implication on two operands.
NotNegationReturns the logical opposite of an operand.
OrDisjunctionReturns True if either of its operands is True.
XorExclusionReturns True if only one of its operands is True.
String Concatenation Operator
&ConcatenationAppends one string to another.

Operator Precedence

Type: Definition
Description: Precedence is very important in every computer language and VBScript is no exception. The order of precedence indicates which operator should be evaluated first. However, you can use parentheses to explicitly change the order of evaluation. Expressions inside parentheses are always evaluated before expressions outside the parentheses. Otherwise, regular operator precedence is always used.

Table 28.34 lists the operators in order of precedence. When operators have equal precedence, they are evaluated left to right as they appear in the expression.

Table 28.34  VB Script's Order of Operator Precedence

OperatorDescription
Arithmetic Operators 
^Exponentiation
-Unary negation
*Multiplication
/Division
\Integer division
ModModulus
+Addition
-Subtraction
&String concatenation
Comparison Operators
All comparison operators have the same level of precedence.
Logical Operators
NotNegation
AndConjunction
OrDisjunction
XorExclusion
EqvEquivalence
ImpImplication

Option Explicit

Syntax: Option Explicit
Type: Keyword
Synopsis: Ensures that all variables are explicitly declared.
Description: When the Option Explicit statement is placed at the top of your script, an error will be generated by any variable that is not explicitly defined. The error is generated when the web browser reads the HTML document file. Requiring every variable to be explicitly declared means that you can't misspell variables without generating an error message-a great bug prevention feature.

Example:

<HTML>
<HEAD>
<SCRIPT>
<!--
Option Explicit ' must be the first line
' in the script.

Dim lngTemp
-->
</SCRIPT>
</HEAD>
</HTML>

See Also: Dim

Options

Syntax: element.Options
Type:Read-Only Property
Synopsis:Gets the <OPTIONS> tag for element.
Description:The element specified must be a Select element. An object with the following properties is returned:

PropertyDescription
DefaultSelectedGets the currently selected attribute.
IndexGets the index of an option.
LengthGets the number of options in the selected object.
NameGets the name of the selected object.
SelectedUsed to programmatically select an option.
SelectedIndexGets the index of the selected option.
TextGets the text to be displayed.
ValueGets the value attribute.

Or

Syntax: result = operand1 Or operand2
Type: Operator
Synopsis: Returns True if either operand is True.
Description: If either operand is Null, then Null is returned. If the operands are numeric, then a bitwise comparison of identically positioned bits is performed.

See Also: Operators

Parent

Syntax: window.Parent
Type: Read-Only Property - applies to a Window object
Synopsis: Returns a reference to the parent window object.
Description: The parent of the current window is the containing frame. If there is no containing frame, then the current window object is returned. Therefore, you can tell if the current document is inside a frame by comparing the current window object with the parent object. If they are the same, then no frame is present. The example section shows how this could be done.

Example:

<!-- This document shows how to determine if
the current document is inside a frame.
-->
<HTML>
<HEAD>
<TITLE>VB Script Example Page</TITLE>
<script language="VBScript">
<!--
Function IsFrame
IsFrame = NOT(window Is window.parent)
End Function
-->
</script>
</HEAD>
<BODY>
<H1>VB Script Example Page</H1>
<SCRIPT language="VBScript">
<!--
Document.Open
If IsFrame = True Then
Document.Write "Frames"
Else
Document.Write "No Frames"
End If
Document.Close
-->
</SCRIPT>
</BODY>
</HTML>

Pathname

Syntax 1: link.Pathname
Syntax 2: location.Pathname
Syntax 3: location.Pathname = path
Type: Property
Synopsis: Gets the path for link or location. Sets the path for location.
Description: The path part of a URL is between the host part and the search or hash parts.

Port

Syntax 1: link.Port
Syntax 2: location.Port
Syntax 3: location.Port = portnumber
Type: Property
Synopsis: Gets the port for link or location. Sets the port for location.
Description: This property always returns the empty string ("") for the file: protocol.

Procedures

Type: Definiton
Description: A function is a user-defined or built-in method that performs a task. It can also return a value. Functions are universal and do not need to be associated with an object to run, while methods are integrated with objects.

As a general rule, it's best to place function definitions within the <HEAD> tags of a document. This practice ensures that any functions are loaded and ready before the user has a chance to interact with the rest of the page.

All procedures can accept information in the form of arguments or parameters. For example, if you have a function that calculates the floor space of a room, you'll need to tell the function the length and width of the room. Parameters are placed inside parentheses immediately after the name of the procedure being called like this:

calcSquareFootage(width, length)

The parentheses are not required until you also use the Call keyword.

If a procedure needs to change a variable used by another procedure or the calling procedure, the variable needs to have script-level scope. (See "Scope").

Prompt

Syntax: result = window.Prompt(prompt [, default])
Type:Method - applies to Window objects
Synopsis:Requests input from the user.
Description:The Prompt method will return the string that the user entered. The prompt parameter is used to display a message, usually a question that indicates what kind of input is needed. The default parameter is used to provide a default answer. The Microsoft documentation indicates that both prompt and default parameters are optional. However, as you can see in Figure 28.9 if they are not specified the string "<undefined>" is used.

Example:

<!-- This document shows how to use the
Confirm method.
-->
<HTML>
<HEAD>
<TITLE>VB Script Example Page</TITLE>
</HEAD>
<BODY>
<H1>VB Script Example Page</H1>
<SCRIPT language="VBScript">
<!--
result = Prompt()
-->
</SCRIPT>
</BODY>
</HTML>

Picture:

Figure 28.9: A prompt box with no parameters specified.

Properties

Type: Definition
Description: Properties are used to describe an object or its current state. A property is defined by assigning it a value. The value can be assigned by the browser, the program, or as the user interacts with the page.

Protocol

Syntax 1: link.Protocol
Syntax 2: location.Protocol
Syntax 3: location.Protocol = protocol
Type: Property
Synopsis: Gets the protocol for link or location. Sets the protocol for location.
Description: The protocol parameters is a string that represents the protocol that you need to use. For example, "ftp:" is used for the file transfer protocol.

Raise

Syntax: Err.Raise(number, [ source, [ description, [helpfile, contextID]]])
Type: Method
Synopsis: Generates a run-time error.
Description: The number parameter indicates the nature of the run-time error and can range from 0 to 65,535.

The optional source parameter is the name of the error generator. If an Automation object generates an error, then source should have the form "myProject.myClass." The default value is the programmatic ID of the current VBScript project.

The optional description parameter describes the error. It defaults to the internal string associated with Err.Number or a generic error message.

The optional helpfile and contextID parameters are used to specify a topic inside a help file that can be used for context-sensitive help.

Randomize

Syntax: Randomize [number]
Type: Intrinsic Math Function
Synopsis: Initializes the random-number generator.
Description: In order to generate "true" random numbers, the random-number generator needs to be reseeded with a different number each time your script starts. If the number parameter is not specified, a number based on the current date and time is used.
See Also: Abs, Atn, Cos, Exp, Log, Math Functions, Rnd, Sin, Sqr, Tan

ReDim

Syntax: ReDim [Preserve] varname(subscripts) [, varname(subscripts)] ...
Type: Keyword
Synopsis: Declares or modifies the bounds for dynamic arrays.
Description: A ReDim statement can be used to allocate or reallocate space to dynamic arrays. There is no limit to the number of times that you can modify the dimensions of an array. Dynamic arrays are created using the Dim statement and empty parentheses.

The Preserve option will let you change an array's dimension and keep its existing data. However, you are limited to changing only the last array dimension. If you reduce the size of the array, you will lose the data in the freed-up element. Increasing the size of the array will result in elements that are either zero (numeric), have a zero-length string (string), or have the Nothing value (object).

Example:

Dim a() ' declare a dynamic array
ReDim a(10, 10) ' allocate memory for a 10x10 array
ReDim Preserve a(10, 15) ' make array larger, but keep the contents.

See Also: Array Variables, Dim, Erase, IsArray, LBound, UBound

Referrer

Syntax: document.Referrer
Type: Read-Only Property
Synopsis: Returns the URL of the referring document.
Description: The referring document is the document that contained the hyperlink that the user clicked to get to document. If there was no referring document, then Null is returned.

Rem

Syntax 1: Rem comment
Syntax 2: ' comment
Type: Keyword
Synopsis: Lets you add comments to your scripts.
Description: Comments are very important. They help you understand the intent behind the simple mechanics of a program. You can use either the Rem keyword or a single quote to create comments. However, most programmers use the single quote syntax. Using the single quote syntax lets you easily add comments to the end of a line of code-as demonstrated in the example.

Example:

REM This is a comment.
' This is another comment.
intA = intB ^ 4 ' yet another comment

Right

Syntax: Right(string, length)
Type: Intrinsic String Function
Synopsis: Returns a copy of length characters taken from the end of string.
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LeftB, Len, LenB, LTrim, Mid, MidB, RightB, Space, StrComp, String, String Functions, Trim, Ucase

RightB

Syntax: RightB(string, length)
Type: Intrinsic String Function
Synopsis: Returns a copy of length bytes taken from the end of string.
Description: RightB is used for binary data.
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LeftB, Len, LenB, LTrim, Mid, MidB, Right, Space, StrComp, String, String Functions, Trim, Ucase

Rnd

Syntax: Rnd[(number)]
Type: Intrinsic Math Function
Synopsis: Returns a random number that is greater than or equal to zero but less than one.
Description: The random numbers are generated using a algorithm that produces a sequence of numbers. If number is not specified or is greater than zero, the next number in the random number sequence is returned. If number is less than zero, then the same number is returned every time. If the number is zero, the previous random number is returned again.

To generate random numbers in a certain range, use this formula: Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Example:

' Simulate a six-sided die-the range is 1 to 6.
intResult = Int((6 - 1 + 1) * Rnd + 1)

' Simulate two six-sided dice-the range is 2 to 12.
intResult = Int((12 - 2 + 1) * Rnd + 2)

See Also: Abs, Atn, Cos, Exp, Log, Math Functions, Randomize, Sin, Sqr, Tan

RTrim

Syntax: RTrim(string)
Type: Intrinsic String Function
Synopsis: Returns a copy of string with no trailing spaces.
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LeftB, Len, LenB, LTrim, Mid, MidB, Right, RightB, Space, StrComp, String, String Functions, Trim, Ucase

<Script>

Syntax: <SCRIPT [EVENT=event] [FOR=object] [LANGUAGE=lang]> ...</SCRIPT>
Type: HTML Tag
Synopsis: Contains script statements inside an HTML document.
Description: The <SCRIPT> tag encloses VBScript statements so that the browser knows that they are executable. If the EVENT attribute is used, it specifies the type of event that the script statements will handle. The FOR attribute is used in conjunction with EVENT and it specifies which object or control the script should be associated with.

One or more VBScript commands can be enclosed in a <SCRIPT> tag. The advent of several scripting languages has made it necessary to identify for the browser which language is being used. For VBScript, the syntax is:

<SCRIPT LANGUAGE="VBScript">
<!--
[statements]
-->
</SCRIPT>

Note the use of HTML comment tags, <!-- and -->. If the page containing the script is used on a browser that is not compatible with the scripting languages, the script statements are normally displayed as any other text on the page, adding clutter and trash to the screen. If you use the comment tags, an incompatible browser ignores the script portion of the document.

See Also: Events, Event Handling

Scope

Type: Definition
Description: When variables are declared inside a procedure, they can only be used by statements inside that procedure. This limitation is referred to as the scope of the variable. Local scope means that a variable has declared inside a procedure. Script-level scope means that a variable was declared outside of all procedures and therefore can be accessed by all of the procedures.

Search

Syntax 1: link.Search
Syntax 2: location.Search
Syntax 3: location.Search = string
Type: Property
Synopsis: Gets the search part of link or location. Sets the search part of location.
Description: The search part of a URL starts with a question mark. For example, in http://www.planet.net/search.pl?trains, the ?trains is the search part of the URL. If the URL has no search part, then Null is returned.

Second

Syntax: Second(time)
Type: Intrinsic Date/Time Function
Synopsis: Returns the seconds value from time-which can range from 0 to 59, inclusive.
See Also: Date, Date/Time Functions, DateSerial, DateValue, Day, Minute, Month, Now, Time, TimeSerial, TimeValue, Weekday, Year

Select

Syntax: element.Select
Type: Method
Synopsis: Selects the contents of element.

Select Case

Syntax: Select Case testexpression [Case expression [statements]] ... [Case Else expression [statements]] End Select
Type: Keyword
Synopsis: Selectively executes a statement block when the expression associated with the statement block equals the testexpression. If no matches are found, then the statement block in the Else clause is executed.
Description: If testexpression matches more than one expression, only the statement block associated with the first matching expression is executed. You can use string values in both the testexpression and expression parts of the Select Case statement.

The Else clause is frequently used to catch unexpected values. For example, if you are processing payroll records by month, the Else clause might be used to catch values that are not in the range of 1 to 12.

SelectedIndex

Syntax: element.SelectedIndex
Type:Read-Only Property
Synopsis:Gets the index for the selected options.
Description:If there are multiple selected options, then the index of the first option selected is returned.

Self

Syntax: window.Self
Type:Read-Only Property - applies to a Window object
Synopsis:Returns an object reference to window.
Description: If window is not specified, the current window object is returned.

Set

Syntax: Set objectvar = { objectexpression | Nothing}
Type: Keyword
Synopsis: Assigns a value to an object variable.
Description: You must use the Set keyword when assigning objects to variables or properties. Memory associated with objectVar can be freed by assigning the special value Nothing to it.

Generally speaking, the values that get assigned will be object references not copies of the object. This means that more than one variable can reference the same object. The Is operator can be used to determine if two variables point to the same object.

Example:

Set index = 0
Set myForm = Document.ValidForm

See Also: Is

SetTimeout

Syntax: timerID = window.SetTimeout(expression, msec, language)
Type:Method - applies to Window objects
Synopsis:Executes a procedure after a specified amount of time has elapsed and returns a timer object.
Description:The expression parameter must evaluate to a procedure name or an object's method. The procedure or method will be executed after msec milliseconds (one second = 1,000 milliseconds). This method is an excellent way to create dialog box timeouts. In the example given previously, the Quit button will be clicked after five seconds.

Example:

clickTimer = setTimeout ("quitButton.OnClick", 5000).

See Also: clearTimeout

Sgn

Syntax: Sgn(number)
Type: Intrinsic Conversion or Math Function
Synopsis: Returns 1 if number is greater than zero, -1 if number is less than zero, and zero if number is zero.

Example:

intResult = Sgn(-10) ' intResult equals -1

See Also: Conversion Functions, Math Functions

Sin

Syntax: Sin(angle)
Type: Intrinsic Math Function
Synopsis: Returns the sine of angle.
Description: The Sin function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the hypotenuse. The result lies in the range -1 to 1. To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by
180/pi. 
See Also: Abs, Atn, Cos, Exp, Log, Math Functions, Randomize, Rnd, Sqr, Tan

Single-Precision Variables

Syntax: Definition
Description: Single-precision variables can have around 45 digits of precision-not even half the size of double-precision regardless of the name. However, since single-precision numbers can fit inside 32 bits and double-precision numbers need 64 bits, extensive calculations will perform faster using single-precision.
See Also: Variables

Source

Syntax 1: Err.Source
Syntax 2: Err.Source = stringexpression
Type: Source
Synopsis: Gets or sets the name of the object or application that originally generated the error.
Description: Source is usually the class name or programmatic ID of the object that caused the error.

Space

Syntax: Space(number)
Type: Intrinsic String Function
Synopsis: Returns a string of number spaces.
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LeftB, Len, LenB, LTrim, Mid, MidB, Right, RTrim, StrComp, String, String Functions, Trim, UCase

Sqr

Syntax: Sqr(number)
Type: Intrinsic Math Function
Synopsis: Returns the square root of number.
See Also: Abs, Atn, Cos, Exp, Log, Math Functions, Randomize, Rnd, Sin, Tan

Status

Syntax 1: window.Status
Syntax 2: window.Status = string
Type: Property - applies to a Window object
Synopsis: Returns or sets the status text for the lower left portion of the status bar.

Example:

' set the default status text.
self.Status = "Ready for Input"

' assign the default status text to a variable
strText = self.Status

StrComp

Syntax: StrComp(string1, string2 [, compare])
Type: Intrinsic String Function
Synopsis: Returns -1 if string1 is less than string2, 0 if they are equal, 1 if string1 is greater than string2, and Null if either string1 or string2 are Null.
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LeftB, Len, LenB, LTrim, Mid, MidB, Right, RTrim, Space, String, String Functions, Trim, UCase

String

Syntax: String(number, character)
Type: Intrinsic String Function
Synopsis: Returns a string that contains character repeated number times.
Description: If character is Null, then the Null value is returned. If the value of character is greater than 255, then it is turned into a valid character code using the modulus operator (character Mod 256).
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LeftB, Len, LenB, LTrim, Mid, MidB, Right, RTrim, Space, StrComp, String Functions, Trim, UCase

String Functions

Type: Definition
Description: VBScript's string functions are listed in Table 28.35.

Table 28.35  VBScript String Functions

FunctionDescription
AscReturns the ANSI code of the first character in a string.
AscBReturns the first byte in a string.
AscWReturns the first Unicode character (32-bits) in a string.
ChrReturns the character associated with a character code.
ChrBReturns the byte associated with a character code.
ChrWReturns the Unicode character associated with a character code.
InStrReturns the location of one string in another.
InStrBReturns the byte position of one string in another.
LCaseReturns a copy of a string with all characters converted to lowercase.
LeftReturns a copy of the beginning of a string.
LeftBReturns a copy of the beginning of a string.
LenReturns the number of bytes it takes to store a variable's value.
LenBReturns the number of bytes it takes to store an expression's value.
LTrimReturns a copy of string without leading spaces.
MidReturns a copy of part of a string.
MidBReturns a copy of part of a string.
RightReturns a copy of the end of a string.
RightBReturns a copy of the end of a string.
RTrimReturns a copy of a string with no trailing spaces.
SpaceReturns a string of a specified number of spaces.
StrCompCompares two strings.
StringReturns a string of a specified character repeated a specified number of times.
TrimReturns a copy of a string with no leading or trailing spaces.
UCaseReturns a copy of a string with all characters converted into uppercase.

String Variables

Syntax: Definition
Description: Strings are defined by a number of characters (up to 2 billion) within double quotes.

Examples:

strTemp = "The Doctor said, \"You're Fine.,\" to me."

See Also: Variables

String Concatenation (&)

Syntax: result = string1 & string2
Type: String Concatenation Operator
Synopsis: Appends string2 to string1.
Description: Although you can also use the + operator to concatenate two character strings, you should use the & operator for concatenation instead. The & operator eliminates ambiguity and provides self-documenting code.
See Also: Operators

Sub

Syntax: Sub name [(arglist)] [statements] End Sub
Type: Keyword
Synopsis: Declares a user-defined subroutine called name.
Description: Sub statements are used to create user-defined subroutines. Subroutines differ from functions because they do not return any value.

All subroutines should be declared towards the beginning of your script in the HEAD section of your HTML page. This ensures that the subroutines will be available for use by later VBScript statements.

arglist is an optional list of arguments or parameters that the subroutine can use. If you would like the subroutine to assign values to the arguments, use the ByVal keyword inside the parameter list.

Note
Subroutines do not return values. Therefore, it seems logical that they should not modify parameters either. If you need to return a value or modify a parameter, try creating a user-defined function instead.

Example:

' Define a subroutine with one parameter.
Sub displayIt(strMsg)
Alert "Error: " & strMsg
End Sub

See Also: Call, Exit, Function, Scope

Submit

Syntax: form.Submit
Type:Method
Synopsis:Sends form information to the server.
See Also:OnSubmit

Subtraction (-)

Syntax: result = operand1 - operand2
Type: Arithmetic Operator
Synopsis: Subtracts operand2 from operand1.
Description: If one of the operands contain the Null value, then the result is Null. If one of the operands contain the Empty value, it is treated as if it were zero.
See Also: Operators

Tan

Syntax: Tan(angle)
Type: Intrinsic Math Function
Synopsis: Returns the tangent of angle.
Description: Tan takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.
See Also: Abs, Atn, Cos, Exp, Log, Math Functions, Randomize, Rnd,
Sin, Sqr 

Target

Syntax 1: form.Target
Syntax 2: form.Target = string
Syntax 3: link.Target
Type: Property
Form Synopsis: Gets or sets the name of the window to display form results in.

Caution
In Internet Explorer v3.0, this property has no effect on the operation of the form.

Link Synopsis: Gets the name of the window-the TARGET attribute of the HTML <A> tag-to display the URL in.

Time

Syntax: Time
Type: Intrinsic Date/Time Function
Synopsis: Returns the current system time.
See Also: Date, Date/Time Functions, DateSerial, DateValue, Day, Minute, Month, Now, Second, TimeSerial, TimeValue, Weekday, Year

TimeSerial

Syntax: TimeSerial(hour, minute, second)
Type: Intrinsic Conversion and Date/Time Function
Synopsis: Returns a Date variable that represents hour, minute, and second
Description: The hour parameter can range from 0 (midnight) to 23 (11:00 P.M.). The minute and second parameters can range from 0 to 59. You can pass expressions instead of literals to perform some basic date arithmetic. The example shows how to subtract two from a given month. Parameters that are too large to fit into the normal range will carry-over into the next larger unit. For instance, a minute parameter of 70 will increment the hour parameter. If one of the parameters fall outside the range -32,768 to 32,767, or if the date specified by the three arguments falls outside the acceptable range of times, an error occurs.
See Also: Date, Date/Time Functions, DateSerial, DateValue, Day, Minute, Month, Now, Second, Time, TimeValue, Weekday, Year

TimeValue

Syntax: TimeValue(time)
Type: Intrinsic Conversion and Date/Time Function
Synopsis: Returns a Date value representing time.
Description: The time parameter can range from 0:00:00 (midnight) to 23:59:59 (11:59:59 P.M.). If time is Null, then Null is returned. The DateValue function understands both 12-hour and 24-hour clocks. If time contains date information, it is ignored. However, if time includes invalid date information, an error occurs.
See Also: Date, Date/Time Functions, DateSerial, DateValue, Day, Minute, Month, Now, Second, Time, TimeSerial, Weekday, Year

Title

Syntax: document.Title
Type: Read-Only Property
Synopsis: Returns a string with document's title.

Top

Syntax: window.Top
Type:Read-Only Property - applies to a Window object
Synopsis:Returns a Window object that represents the top-most window.

Trim

Syntax: Trim(string)
Type: Intrinsic String Function
Synopsis: Returns a copy of string with no leading or trailing spaces.
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LeftB, Len, LenB, LTrim, Mid, MidB, Right, RTrim, Space, StrComp, String, String Functions, UCase

Type Conversion

Type: Definition
Description: A variable's type depends on the kind of information it contains (see the "Literals" entry). VBScript is loosely typed, meaning that you don't need to declare what kind of variables you are using. The data type is automatically assigned depending on the value assigned to the variable.

VBScript automatically changes the data type of the variable depending on the operation taking place. The best example of automatic data type conversion involves the string concatenation operator. The follow statements serve to illustrate type conversion.

' example 1
var oneString = "1";
var oneInt = 1
var oneConcatenate = oneString + oneInt ' results in "11"
var oneAddition = oneInt + oneString ' results in 2

In the first addition statement, the first operand is a string. VBScript assumes that the operation is to join two strings. When VBScript encounters an integer as the second operand, it converts the value of the variable into a string to meet its own expectations.

The "Conversion Functions" entry has a list of functions that can convert from one data type to another.

See Also: Conversion Functions, Variable Testing

UBound

Syntax: UBound(arrayname [, dimension])
Type: Intrinsic Array Function
Synopsis: Returns the largest subscript for dimension of an arrayname.
Description: You can use LBound in conjunction with UBound to find out an array's size.

Example:

Dim C(50, 10) ' declare an array
d1 = UBound(C, 1) ' d1 equals 49
d2 = UBound(C, 2) ' d2 equals 9

See Also: Array Variables, Dim, Erase, IsArray, LBound, ReDim

UCase

Syntax: UCase(string)
Type: Intrinsic String Function
Synopsis: Returns a copy of string with all characters converted into uppercase.
Description: If string is Null, then Null is returned.
See Also: Asc, AscB, AscW, Chr, ChrB, ChrW, InStr, InStrB, LeftB, Len, LenB, LTrim, Mid, MidB, Right, RTrim, Space, StrComp, String, String Functions, Trim

Negation (-)

Type: Operator
Description: When the unary negation operator is placed in front of an expression, it means that the negative value of the expression is used. The unary negation operation and the subtraction operation both use the - character.

Example:

intA = 234 ' intA equals 234.
intB = -intA ' intB equals -234.

See Also: Operators

UserAgent

Syntax: navigator.UserAgent
Type:Read-Only Property
Synopsis:The name of the current application user agent.
Description:This property returns "Mozilla/2.0 (compatible; MSIE 3.0A; Windows 95)" when using Microsoft Internet Explorer v3.0 (4.70.1158).

Example:

' Display the application version
Alert Navigator.UserAgent

Value

Syntax 1: element.Value
Syntax 2:element.Value = string
Type:Property
Synopsis:Gets or sets the value of element.

Variables

Type: Definition
Description: The variant data type can hold any type of information and it is the only type of data that VBScript uses. All VBScript functions return variant data types.

If a variable holds a number and is being used in a numeric context, then it behaves like a number. If the variable is used in a string content, VBScript will silently convert the number into a string. Uninitialized variables have the Empty value.

Some property names are reserved words-which means that you can't use them for your own variable names. In order to avoid having to remember which property names are reserved and which are not, the "Variable Naming" section suggests some prefixes that you can use to distinguish your variable names.

VBScript has 12 subtypes that automatically come into play depending on the context:

Table 28.36  VBScript's Variant Subtypes

SubtypeDescription
EmptyAn uninitialized variable.
NullA variable containing no valid data.
BooleanThe variable can be either True or False.
ByteThe variable is in the range 0 to 255.
IntegerThe variable is in the range -32,768 to 32,767.
LongThe variable is in the range -2,147,483,648 to 2,147,483,647.
SingleThe variable is a single-precision floating-point number that can be over 35 digits in length.
DoubleThe variable is a double-precision floating-point number that can be over 300 digits in length.
DateThe variable contains a date/time between 01/01/0100 and 12/31/9999.
StringThe variable contains a sequence of characters that can be up to about two billion characters in length.
ObjectThe variable contains an object.
ErrorThe variable contains an error number.
See Also: Boolean Variables, Empty, Null

Variable Naming

Type: Guideline
Description: Because VBScript is so loosely typed, it is critical that you remember what type of data is stored in each of your variables. One way of doing this is to create your own variable naming guidelines. Table 28.37 lists some prefixes that you can use to help get you started on your own guidelines.

Table 28.37  Suggested Variable Naming Guidelines

PrefixData Type
aniAnimated button control
aryArray
blnBoolean
btnButton control
bytByte
cboCombo control
chkCheckbox control
chtChart control
cmdCommand button
cstConstant (actually a pseudo-constant)
dlgDialog control
dblDouble-precision
dtmDate/time
errError
fraFrame object
hsbHorizontal scrollbar control
imgImage control
intInteger
lblLabel control
linLine control
lnkHyperlink
lstList control
lngLong
objObject
pnlPanel control
sldSlider control
sngSingle-precision
spnSpin button control
strString
txtText control
vsbVertical scrollbar control

Variant

Type: Definition
Description: Variant is the single data type that VBScript supports. Each variant variable can contain any type of data. In fact, there are 12 data subtypes (which are described in the "Variables" entry). VBScript normally does an excellent job of automatically converting between the subtypes-matching the subtype to the task at hand. However, if you run into a problem use one of the data type conversion functions (listed in the See Also section)

One of the few times you might have trouble with the variant data type is when using the + sign. The + sign can be used to both add two numbers together and concatenate two strings. VBScript decides between adding and concatenating by checking the subtype of the first operand. If the first operand is numeric, the second operand is converted to a number and added to the first. Otherwise, string concatenation is performed. If you are not careful, you might not get the results you expect.

Tip
Always use the & operator for string concatenation to ensure consistent results.

See Also: Variables

Variant Testing Functions

Type: Definition
Description: VBScript provides several functions that let you determine what type of data is in a Variant variable.

Table 28.38  VBScript's Variant Testing Functions

FunctionDescription
IsArrayReturns true if its parameter is an array.
IsDateReturns true if its parameter is a date.
IsEmptyReturns true if its parameter has a Empty value.
IsNullReturns true if its parameter has a Null value.
IsNumericReturns true if its parameter is numeric.
IsObjectReturns true if its parameter is an object reference.
VarTypeReturns a value representing the data subtype of its parameter.

VarType

Syntax: VarType(varname)
Type: Intrinsic Function
Synopsis: Returns a value representing the data subtype of varname.
Description: The VarType function never returns the array subtype value by itself. It is always added to some other value to indicate an array of a particular type. The value for Variant is only returned when it has been added to the value for Array to indicate that the argument to the VarType function is an array. For example, the value returned for an array of integers is calculated as 8192 + 2, or 8194. If an object has a default property, VarType (object) returns the type of its default property.

Table 28.39  Return Values for the VarType Functon

Value
Description
0
Empty (uninitialized)
1
Null (no valid data)
2
Integer
3
Long integer
4
Single-precision floating-point number
5
Double-precision floating-point number
6
Currency (not supported by VBScript)
7
Date
8
String
9
Automation Object
10
Error
11
Boolean
12
Variant (used only with arrays of Variants)
13
Non-automation object
17
Byte
8192
Array

Example:

' create some pseudo-constants.
cstLong = 3
cstArray = 8192

lngTemp = CLng(324)
If VarType(lngTemp) = cstLong Then
Alert "It's a long variable"
Else
Alert "It's not long."
End If

' put the subtype of an array elements into
' the intElementType variable. If the variable
' is not an array, then make the element type
' equal to Null.
If VarType(anyVar) And cstArray Then
intElementType = VarType(anyVar) - cstArray
Else
intElementType = Null
End If

See Also: IsArray, IsDate, IsEmpty, IsNull, IsNumeric, IsObject, Variables

VBScript Statements

Type: Definition
Description: The statements used to control program flow in VBScript are similar to Visual Basic. A statement can span several lines if needed or several statements can be placed on the same line provided they are separated by a colon character.

Table 28.40  VB Statement Types

StatementDescription
CallRuns a Sub or Function procedure.
DimDeclares script-level or procedure-level variables.
DoRepeatedly executes a statement block while a condition is True or until a condition becomes True.
End FunctionEnds a function definition.
End SubEnds a subroutine definition.
ExitExits a block of statements or ends the script.
ForRepeatedly executes a statement block for a specific number of times.
FunctionCreates a user-defined function.
IfOptionally Executes statements based on a conditional expression.
OptionEnsures that all variables are Explicit explicitly declared.
ReDimDeclares or modifies the bounds for dynamic arrays.
SetAssigns a value to an object variable.
SubCreates a user-defined subroutine.
WhileNot recommended, use Do instead.

vLinkColor

Syntax 1: document.vLinkColor = rgbValue
Syntax 2:document.vLinkColor = string
Type:Property
Synopsis:Gets or sets document's visited link color.
Description:You can set the color by specifying a RGB value in hexadecimal or by specifying a color name. The "Color Names" entry lists all of the color names that you can use.

You can only set this property while the document is being parsed. An OnLoad event handler procedure is a good place to set document properties.

Weekday

Syntax: Weekday(date, [firstdayofweek])
Type: Intrinsic Date/Time Function
Synopsis: Returns the day of the week (from one for Sunday to seven for Saturday) that date falls on.
Description: You can change the beginning day of the week by providing a firstdayofweek parameter.

Table 28.41  Values for the firstdayofweek Parameter

Value
Description
0
Use NLS API setting.
1
Sunday (this is the default value)
2
Monday
3
Tuesday
4
Wednesday
5
Thursday
6
Friday
7
Saturday

See Also: Date, Date/Time Functions, DateSerial, DateValue, Day, Minute, Month, Now, Second, Time, TimeSerial, TimeValue, Year

While

Type: Keyword
Synopsis: The While statement, while supported, is no longer recommended. Use a Do...Loop statement instead.

Whitespace

Type: Definition
Description: Whitespace refers to spaces, tabs, and carriage return characters-in short, any character that can be used to create white space on a piece of paper.

Window

Type: Object
Synopsis: Represents a window in the browser.
Description: You can use "Window" to refer to the object associated with the current window. However, using the "Window" object name is usually not needed because your code will probably be inside the window's scope. Window objects are at the top of the object hierarchy. They are directly analogous to browser windows.

Table 28.42  Objects Contained Inside a Window Object

ObjectDescription
DocumentRepresents the document in the current windows
FrameEach element in this array represents one of the frames of the browser.
HistoryRepresents the history list of the browser.
LocationRepresents the URL of the current document.
NavigatorRepresents the browser application.
ScriptRepresents all of the scripts in the current window.

Table 28.43  Events of Window Objects

EventPage Number Description
OnLoadp. 888Happens when a document is loaded.
OnUnloadp. 891Happens when a document is unloaded.

Table 28.44  Methods of Window Objects

MethodDescription
AlertDisplays an alert message box.
ClearTimeoutClears a specified timer that was created by SetTimeout.
CloseCloses a browser window.
ConfirmDisplays a message box with OK and Cancel buttons.
NavigateOpens a new URL in the window.
OpenCreates a new browser window.
PromptPrompts the user for input using a dialog box.
SetTimeoutCalls a specified function after a specified amount of time.

Table 28.45  Properties of Window Objects

PropertyDescription
DefaultStatusGets or sets the default status text for the lower left portion of the status bar.
DocumentGets the Document object associated with a window.
FramesGets an array of frames contained in a window.
HistoryGets the History object of a window.
LocationGets the Location object for a window.
NameGets the name of a window.
NavigatorGets the Navigator object associated with a window.
OpenerGets the Window object that represents the window that opened the current window.
ParentGets a reference to the parent window object.
SelfGets an object reference to a window.
StatusGets or sets the status text for the lower left portion of the status bar.
TopGets a Window object that represents the top-most window.

Write

Syntax: document.Write(string)
Type: Method
Synopsis: Places string into document.
Description: The Write method will append string to document. Remember that string needs to have HTML tags if formatted output is needed.

WriteLn

Syntax: document.WriteLn(string)
Type: Method
Synopsis: Places string into document and adds a newline character.
Description: The WriteLn method will append string to document. Remember that string needs to have HTML tags if formatted output is needed and that the newline character does not show up in the brower's window unless the <PRE> HTML ta