Chapter 48

ActiveX Scripting: VB Script and Jscript

by Jim O'Donnell


CONTENTS

In addition to Netscape's JavaScript language, Microsoft has introduced its own scripting language, Visual Basic Script (VB Script), which is based on the Visual Basic and Visual Basic for Applications languages. Just as those two languages made it much easier to create applications for Windows and within the Microsoft Office suite, respectively, VB Script was designed as a language for easily adding interactivity and dynamic content to Web pages. VB Script gives Web authors the ability to use Internet Explorer, and other compatible Web browsers and applications, to execute scripts to perform a wide variety of uses. These uses include verifying and acting on user input, customizing Java applets, interacting with and customizing ActiveX Controls and other OLE-compatible applications, and many other things.

What Is VB Script?

Since Microsoft began its big push into the Internet and World Wide Web arena in December 1995, it has been pursuing the Web industry leader, Netscape, with a two-pronged approach. On one hand, it has been adding features to its own Web browser, Internet Explorer, in order to make it more compatible with Netscape Navigator. Some of these added features include support of HTML extensions (such as frames), the ability to execute Java applets, and compatibility with the JavaScript scripting language.

The other element of Microsoft's approach is to break new ground. Not content to play catch-up with Netscape, Microsoft has introduced its own new technologies and innovations. Its HTML extensions were discussed in Chapter 16, "Internet Explorer-Specific HTML Extensions." Microsoft's biggest innovations, however, are a collection of technologies called ActiveX Technologies. Elements of ActiveX Technologies are discussed in other parts of this book, which are cited in the cross-reference on this page. Another element, ActiveX Scripting, includes support for JavaScript and Microsoft's own Visual Basic Script (VB Script).

Microsoft's ActiveX Scripting

However, ActiveX Scripting is more than just support for VB Script and JavaScript. Microsoft has developed a standard to allow its Web browser, and other compatible applications, to support arbitrary scripting engines. Vendors can develop scripting engines of their own that can be used with Internet Explorer, as long as they conform to the ActiveX Scripting standard. Microsoft discusses ActiveX Scripting in greater detail within the Internet Explorer Web site at http://www.microsoft.com/ie/ie3/activescript.htm, and under its Internet developer Web site at http://www.microsoft.com/intdev/sdk/docs/olescrpt/.

ON THE WEB
http://www.microsoft.com/intdev/sdk/docs/olescrpt/  This site gives you access to the specifications of Microsoft's ActiveX Scripting technologies.

The first two examples of ActiveX Scripting languages are JScript, Microsoft's open implementation of the JavaScript language, and VB Script.

VB Script

Like JavaScript, VB Script allows you to embed commands into an HTML document. When a user of a compatible Web browser (currently only Internet Explorer or Netscape Navigator with the ScriptActive plug-in from Ncompass Labs) downloads your page, your VB Script commands are loaded by the Web browser along with the rest of the document and are run in response to any of a series of events. Again, like JavaScript, VB Script is an interpreted language; Internet Explorer interprets the VB Script commands when they are loaded and run. They do not first need to be compiled into executable form by the Web author who uses them.

VB Script is a fast and flexible subset of Microsoft's Visual Basic and Visual Basic for Applications languages, and is designed to be easy to program in and quick in adding active content to HTML documents. The language elements are mainly ones that will be familiar to anyone who has programmed in just about any language, such as If...Then...Else blocks and Do, While, and For...Next loops, and a typical assortment of operators and built-in functions. This chapter will take you to the heart of the VB Script language and show you examples of how to use it to add interaction and increased functionality to your Web pages.

NOTE
If you are familiar with JavaScript, or have read the previous chapter's discussion of it, you will find parts of this chapter to be very similar. That's because JavaScript and VB Script are similar languages with similar syntax, which can perform many of the same functions.
So, if you know JavaScript, you can probably skip ahead and look for the examples in the "VB Script and Web Browsers" section and look through the "Example VB Script Applications." Finally, you should read the "What Scripting Language Should You Use?" section at the end of this chapter.

Why Use a Scripting Language?

Although HTML provides a good deal of flexibility to page authors, it is static by itself; once written, HTML documents can't interact with the user other than by presenting hyperlinks. Creative use of CGI scripts (which run on Web servers) has made it possible to create more interesting and effective interactive sites, but some applications really demand programs or scripts that are executed by the client.

VB Script allows Web authors to write small scripts that execute on the users' browsers instead of on the server. For example, an application that collects data from a form and then posts it to the server can validate the data for completeness and correctness before sending it to the server. This can greatly improve the performance of the browsing session, since users don't have to send data to the server until it's been verified as correct.

Another important use of Web browser scripting languages like VB Script comes as a result of the increased functionality being introduced for Web browsers in the form of Java applets, plug-ins, ActiveX Controls, and VRML objects and worlds. Each of these things can be used to add extra functions and interactivity to a Web page. Scripting languages act as the glue that binds everything together. A Web page might use an HTML form to get some user input and then set a parameter for an ActiveX Control based on that input. Usually, it is a script that will actually carry this out.

What Can VB Script Do?

VB Script provides a fairly complete set of built-in functions and commands, allowing you to perform math calculations, manipulate strings, play sounds, open up new windows and new URLs, and access and verify user input to your Web forms.

Code to perform these actions can be embedded in a page and executed when the page is loaded. You can also write functions that contain code that's triggered by events you specify. For example, you can write a VB Script method that is called when the user clicks the Submit button of a form, or one that is activated when the user clicks a hyperlink on the active page.

VB Script can also set the attributes, or properties, of ActiveX Controls, Java applets, and other objects present in the browser. This way, you can change the behavior of plug-ins or other objects without having to rewrite them. For example, your VB Script code could automatically set the text of an ActiveX Label Control based on what time the page is viewed.

VB Script, Visual Basic, and Visual Basic for Applications

VB Script is a subset of the Visual Basic and Visual Basic for Applications languages. If you are familiar with either of these two languages, programming in VB Script will be easy. Just as Visual Basic was meant to make the creation of Windows programs easier and more accessible, and Visual Basic for Applications was meant to do the same for Microsoft Office applications, VB Script is meant to give an easy-to-learn yet powerful means for adding interactivity and increased functionality to Web pages.

How Does VB Script Look in an HTML Document?

VB Script commands are embedded in your HTML documents, just as with JavaScript and other scripting languages. Embedded VB scripts are enclosed in the HTML container tag <SCRIPT>...</SCRIPT>. The <LANGUAGE> attribute of the <SCRIPT> tag specifies the scripting language to use when evaluating the script. For VB Script, the scripting language is defined as LANGUAGE="VBS".

VB Script resembles JavaScript and many other computer languages you may be familiar with. It bears the closest resemblance, as you might imagine, to Visual Basic and Visual Basic for Applications because it is a subset of these two languages. The following are some of the simple rules you need to follow for structuring VB scripts:

VB Script Programming Hints

You should keep a few points in mind when programming with VB Script. These hints will ease your learning process and make your HTML documents that include VB scripts more compatible with a wider range of Web browsers.

Hiding Your Scripts  Because VB Script is a new product and is currently supported only by Internet Explorer 3-though Oracle, Spyglass, NetManage, and other companies plan to license the technology for future versions of their Web browsers-you'll probably be designing pages that will be viewed by Web browsers that don't support it. To keep those browsers from misinterpreting your VB script, wrap your scripts as follows:

<SCRIPT LANGUAGE="VBS">
<!-- This line opens an HTML comment
VB Script commands...
<!-- This line closes an HTML comment -->
</SCRIPT>

The opening <!-- comment causes Web browsers that do not support VB Script to disregard all text they encounter, until they find a matching -->, so they don't display your script. Make sure that your <SCRIPT>...</SCRIPT> container elements are outside the comments, though; otherwise, even compatible Web browsers will ignore the script.

Comments  Including comments in your programs to explain what they do is usually good practice-VB Script is no exception. The VB Script interpreter ignores any text marked as a comment, so don't be shy about including them. Comments in VB Script are set off using the REM statement (short for remark) or by using a single quotation mark (') character. Any text following the REM or single quotation mark, until the end of the line, is ignored. To include a comment on the same line as another VB Script statement, you can use either REM or a single quotation mark. However, if you use REM, you must separate the statement from the REM with a colon. Some of the ways of including HTML and VB Script comments in a script are shown in the followng script fragment:

<SCRIPT LANGUAGE="VBS">
<!-- This line opens an HTML comment
REM This is a VB Script comment on a line by itself.
' This is another VB Script comment
customer.name = "Jim O'Donnell"        'Inline comment
customer.address = "1757 P Street NW"  :REM Inline REM comment (note the :)
customer.zip = "20036-1303"
<!-- This line closes an HTML comment -->
</SCRIPT>

Elements of the VB Script Language

As a subset of Visual Basic and Visual Basic for Applications, VB Script doesn't have as much functionality. It is intended to provide a quicker and simpler language for enhancing Web pages and servers. This section discusses some of the building blocks of VB Script and how they are combined into VB Script programs.

VB Script Identifiers

An identifier is just a unique name that VB Script uses to identify a variable, method, or object in your program. As with other programming languages, VB Script imposes some rules on what names you can use. All VB Script names must start with an alphabetic character and can contain both uppercase and lowercase letters and the digits 0 through 9. They can be as long as 255 characters, though you probably don't want to go much over 32 or so.

Unlike JavaScript, which supports two different ways for you to represent values in your scripts, literals and variables, VB Script has only variables. The difference in VB Script, then, is one of usage. You can include literals-constant values-in your VB Script programs by setting a variable equal to a value and not changing it. We will continue to refer to literals and variables as distinct entities, though they are interchangeable.

Literals and variables in VB Script are all of type variant, which means that they can contain any type of data that VB Script supports. It is usually a good idea to use a given variable for one type and explicitly convert its value to another type as necessary. The following are some of the types of data that VB Script supports:

Objects, Properties, Methods, and Events

Before you proceed further, you should take some time to review some terminology that may or may not be familiar to you. VB Script follows much the same object model followed by JavaScript, and uses many of the same terms. In VB Script, just as in JavaScript-and in any object-oriented language for that matter-an object is a collection of data and functions that have been grouped together. An object's data is known as its properties, and its functions are known as its methods. An event is a condition to which an object can respond, such as a mouse click or other user input. The VB Script programs that you write make use of properties and methods of objects, both those that you create and those objects provided by the Web browser, its plug-ins, ActiveX Controls, Java applets, and the like.

TIP
Here's a simple guideline: An object's properties are the information it knows, its methods are how it can act on that information, and events are what it responds to.

NOTE
A very important, and a little confusing, thing to remember is that an object's methods are also properties of that object. An object's properties are the information it knows. The object certainly knows about its own methods, so those methods are properties of the object right alongside its other data.

Using Built-In Objects and Functions  Individual VB Script elements are objects. For example, literals and variables are objects of type variant, which can be used to hold data of many different types. These objects also have associated methods, ways of acting on the different data types. VB Script also allows you to access a set of useful objects that represent the Web browser, the currently displayed page, and other elements of the browsing session.

You access objects by specifying their names. For example, the active document object is named document. To use document's properties or methods, you add a period and the name of the method or property you want. For example, document.title is the title property of the document object.

Using Properties  Every object has properties-even literals. To access a property, just use the object name followed by a period and the property name. To get the length of a string object named address, you can write the following:

address.length

You get back an integer that equals the number of characters in the string. If the object you're using has properties that can be modified, you can change them in the same way. To set the color property of a house object, just write the following:

house.color = "blue"

You can also create new properties for an object just by naming them. For example, say you define a class called customer for one of your pages. You can add new properties to the customer object as follows:

customer.name = "Jim O'Donnell"
customer.address = "1757 P Street NW"
customer.zip = "20036-1303"

Because an object's methods are just properties, you can easily add new properties to an object by writing your own function and creating a new object property using your own function name. If you want to add a Bill method to your customer object, you can write a function named BillCustomer and set the object's property as follows:

customer.Bill = BillCustomer;

To call the new method, you just write the following:

customer.Bill()

VB Script Language Elements

While VB Script is not as flexible as C++ or Visual Basic, it's quick and simple. Since it is easily embedded in your Web pages, adding interactivity or increased functionality with a VB Script is easy-a lot easier than writing a Java applet to do the same thing (though, to be fair, you can do a lot more with Java applets). This section covers some of the nuts and bolts of VB Script programming.

A full language reference for VB Script, as well as Microsoft's tutorial for VB Script programming, is included on the CD-ROMs that accompany this book. As VB Script is a new and evolving language, you can get up-to-the-minute information on it at the Microsoft VB Script Web site at http://www.microsoft.com/vbscript/.

VB Script Variables

VB Script variables are all of the type variant, which means that they can be used for any of the supported data types. The types of data that VB Script variables can hold are summarized in Table 48.1.

Table 48.1  Data Types that VB Script Variables Can Contain

TypeDescription
EmptyUninitialized and is treated as 0 or the empty string, depending on the context
NullIntentionally contains no valid data
Booleantrue or false
ByteInteger in the range -128 to 127
IntegerInteger in the range -32,768 to 32,767
LongInteger in the range -2,147,483,648 to 2,147,483,647
SingleSingle-precision floating point number in the range -3.402823E38 to -1.401298E-45 for negative values and 1.401298E-45 to 3.402823E38 for positive values
DoubleDouble-precision floating point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values
DateNumber that represents a date between January 1, 100 to December 31, 9999
StringVariable-length string up to approximately 2 billion characters in length
ObjectAny object
ErrorError number

Expressions

An expression is anything that can be evaluated to get a single value. Expressions can contain string or numeric variables, operators, and other expressions, and they can range from simple to quite complex. For example, the following is an expression that uses the assignment operator (more on operators in the next section) to assign the result 3.14159 to the variable pi:

pi = 3.14159

By contrast, the following is a more complex expression whose final value depends on the values of the two Boolean variables Quit and Complete:

(Quit = TRUE) And (Complete = FALSE)

Operators

Operators do just what their name suggests: They operate on variables or literals. The items that an operator acts on are called its operands. Operators come in the two following types:

Assignment Operators  Assignment operators take the result of an expression and assign it to a variable. One feature that VB Script has that most other programming languages do not is that you can change a variable's type on the fly. Consider the example shown in Listing 48.1.


Listing 48.1  Pi-fly.htm-VB Script Variables Can Change Type On the Fly
<HTML>
<HEAD>
<SCRIPT LANGUAGE="VBS">
<!-- Hide this script from incompatible Web browsers!
Sub TypeDemo
    Dim pi
    document.write("<HR>")
    pi = 3.14159
    document.write("pi is " & CStr(pi) & "<BR>")
    pi = FALSE
    document.write("pi is " & CStr(pi) & "<BR>")
    document.write("<HR>")
End Sub
<!-- -->
</SCRIPT>
<TITLE>Changing Pi on the Fly!</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
If your Web browser doesn't support VB Script, this is all you will see!
<SCRIPT LANGUAGE="VBS">
<!-- Hide this script from incompatible Web browsers!
TypeDemo
<!-- -->
</SCRIPT>
</BODY>
</HTML>

This short function first prints the (correct) value of pi. In most other languages, though, trying to set a floating point variable to a boolean value either generates a compiler error or a runtime error. Because VB Script variables can be any type, it happily accepts the change and prints pi's new value: false (see Figure 48.1).

Figure 48.1 : Because VB Script variables are all of type variant, not only their value can be changed, but also their data type.

The assignment operator, =, simply assigns the value of an expression's right side to its left side. In the preceding example, the variable pi gets the floating point value 3.14159 or the boolean value false after the expression is evaluated.

Math Operators  The previous sections gave you a sneak preview of the math operators that VB Script furnishes. As you might expect, the standard four math functions (addition, subtraction, multiplication, and division) work just as they do on an ordinary calculator and use the symbols +, -, x, and /.

VB Script supplies three other math operators:

Comparison Operators  Comparing the value of two expressions to see whether one is larger, smaller, or equal to another is often necessary. VB Script supplies several comparison operators that take two operands and return true if the comparison is true and false if it's not. Table 48.2 shows the VB Script comparison operators.

Table 48.2  VB Script Comparison Operators

Operator
Read It As Returns true When
=
Equals The two operands are equal
<>
Does not equal The two operands are unequal
<
Less than The left operand is less than the right operand
<=
Less than or equal to The left operand is less than or equal to the right operand
>
Greater than The left operand is greater than the right operand
>=
Greater than or equal to The left operand is greater than or equal to the right operand

TIP
The comparison operators also can be used on strings; the results depend on standard lexicographic ordering.

Thinking of the comparison operators as questions may be helpful. When you write

(x >= 10)

you're really saying, "Is the value of variable x greater than or equal to 10?" The return value answers the question, true or false.

Logical Operators  Comparison operators compare quantity or content for numeric and string expressions, but sometimes you need to test a logical value-like whether a comparison operator returns true or false. VB Script's logical operators allow you to compare expressions that return logical values. The following are VB Script's logical operators:

NOTE
Note that the logical implication operator Imp is the only logical operator for which the order of the operands is important.

Note that the And and Or operators don't evaluate the second operand if the first operand provides enough information for the operator to return a value. This process, called short-circuit evaluation, can be significant when the second operand is a function call.

NOTE
Note that all six of the logical operators can also operate on non-Boolean expressions. In this case, the logical operations described previously are performed bitwise, on each bit of the two operands. For instance, for the two integers 19 (00010011 in binary) and 6 (00000110):
19 And 6 = 2 (00000010 in binary)
19 Or 6 = 23 (00010111 in binary)
Not 19 = -20 (11101100 in binary)

String Concatenation  The final VB Script operator is the string concatenation operator &. While the addition operator + can also be used to concatenate strings, using & is better because it is less ambiguous.

Controlling Your VB Scripts

Sometimes the scripts that you write are very simple and execute the same way each time they are loaded-for example, a script to display a graphic animation. However, in order to write a script that will perform different functions, depending on different user inputs or other conditions, you will eventually need to add a little more sophistication to your script. VB Script provides statements and loops for controlling the execution of your programs based on a variety of inputs.

Testing Conditions  VB Script provides one control structure for making decisions-the If...Then...Else structure. To make a decision, you supply one or more expressions that evaluate to true or false; which code is executed depends on what your expressions evaluate to.

The simplest form of If...Then...Else uses only the If...Then part. If the specified condition is true, the code following the condition is executed; if not, that code is skipped. For example, in the following code fragment, the message appears only if the variable x is less than pi:

if (x < pi) then document.write("x is less than pi")

You can use any expression as the condition. Since expressions can be nested and combined with the logical operators, your tests can be pretty sophisticated. Also, using the multiple statement character, you can execute multiple commands, as in the following:

if ((test = TRUE) And (x > max)) then max = x : test = FALSE

The else clause allows you to specify a set of statements to execute when the condition is false. In the same single line form shown in the preceding line, your new line appears as follows:

if (x > pi) then test = TRUE else test = FALSE

A more versatile use of the If...Then...Else allows multiple lines and multiple actions for each case. It looks something like the following:

if (x > pi) then
    test = TRUE
    count = count + 1
else
    test = FALSE
    count = 0
end if

Note that with this syntax, additional test clauses using the elseif statement are permitted. For instance, you could add one more clause to the previous example:

if (x > pi) then
    test = TRUE
    count = count + 1
elseif (x < -pi) then
    test = TRUE
    count = count - 1
else
    test = FALSE
    count = 0
end if

Repeating Actions  If you want to repeat an action more than once, VB Script provides a variety of constructs for doing so. The first, called a For...Next loop, executes a set of statements some number of times. You specify three expressions: an initial expression, which sets the values of any variables you need to use; a final value, which tells the loop how to see when it's done; and an increment expression, which modifies any variables that need it. Here's a simple example:

for count = 0 to 100 step 2
    document.write("Count is " & CStr(count) & "<BR>")
next

In this example, the expressions are all simple numerical values. The initial value is 0, the final value is 100, and the increment is 2. This loop executes 51 times and prints out a number each time.

The third form of loop is the While...Wend loop. It executes statements as long as its condition is true. For example, you can rewrite the first For...Next loop as follows:

count = 0
while (count <= 100)
    document.write("Count is " & CStr(count) & "<BR>")
    count = count + 2
wend

The last type of loop is the Do...Loop, which has several forms, which either test the condition at the beginning or the end. The test can either be a Do While or Do Until, and can occur at the beginning or end of the loop. If a Do While test is done at the beginning, the loop executes as long as the test condition is true, similar to the While...Wend loop. Here's an example:

count = 0
do while (count <= 100)
    document.write("Count is " & CStr(count) & "<BR>")
    count = count + 2
loop

An example of having the test at the end, as a Do...Until, can also yield equivalent results. In that case, the loop looks like the following:

count = 0
do
    document.write("Count is " & CStr(count) & "<BR>")
    count = count + 2
loop until (count = 102)

One other difference between these two forms is that when the test is at the end of the loop, as in the second case, the commands in the loop are executed at least once. If the test is at the beginning, that is not the case.

Which form you prefer depends on what you're doing. For...Next loops are useful when you want to perform an action a set number of times. While...Wend and Do...Loop loops, while they can be used for the same purpose, are best when you want to keep doing something as long as a particular condition remains true.

NOTE
The For...Next and Do...Loop loops also have a way to exit the loop from inside-the End For and End Do statements, respectively. Normally, these tests would be used as part of a conditional statement, such as:
for i = 0 to 100
x = UserFunc()
document.write("x[" & CStr(i) & "] = " & CStr(x) & "<BR>")
if (x > max) end for
next

Other VB Script Statements

This section provides a quick reference to some of the other VB Script statements. The following formatting is used:

The Call statement  The Call statement calls a VB Script Sub or Function procedure, as follows.

Syntax:

Call MyProc([arglist])

or

MyProc [arglist]

Note that arglist is a comma-delimited list of zero or more arguments to be passed to the procedure. When the second form is used, omitting the Call statement, the parentheses around the argument list, if any, must also be omitted.

The Dim statement  The Dim statement is used to declare variables and also to allocate the storage necessary for them. If you specify subscripts, you can also create arrays.

Syntax:

Dim varname[([subscripts])][,varname[([subscripts])],...]

The Function and Sub Statements  The Function and Sub statements declare VB Script procedures. The difference is that a Function procedure returns a value, and a Sub procedure does not. All parameters are passed to functions by value-the function gets the value of the parameter but cannot change the original value in the caller.

Syntax:

[Static] Function funcname([arglist])
    statements...
    funcname = returnvalue
End

and

[Static] Sub subname([arglist])
    statements...
End

Variables can be declared with the Dim statement within a Function or Sub procedure. In this case, those variables are local to that procedure and can only be referenced within it. If the Static keyword is used when the procedure is declared, then all local variables retain their value from one procedure call to the next.

The On Error Statement  The On Error statement is used to enable error handling.

Syntax:

On Error Resume Next

On Error Resume Next enables execution to continue immediately after the statement that provokes the runtime error. Or, if the error occurs in a procedure call after the last executed On Error statement, execution commences immediately after that procedure call. This way, execution can continue despite a runtime error, allowing you to build an error-handling routine inline within the procedure. The most recent On Error Resume Next statement is the one that is active, so you should execute one in each procedure in which you want to have inline error handling.

VB Script Functions

VB Script has an assortment of intrinsic functions that you can use in your scripts. A full reference for these functions is given in the VB Script documentation on the CD. Table 48.3 shows the functions that exist for performing different types of operations. (Some functions can be used for several different types of operations, so they are listed multiple times in the table.)

Table 48.3  VB Script Functions

Type of OperationFunction Names
array operationsIsArray, LBound, UBound
conversionsAbs, Asc, AscB, AscW, Chr, ChrB, ChrW, Cbool, CByte, CDate, CDbl, CInt, CLng, CSng, Cstr, DateSerial, DateValue, Hex, Oct, Fix, Int, Sgn, TimeSerial, TimeValue
dates and timesDate, Time, DateSerial, DateValue, Day, Month, Weekday, Year, Hour, Minute, Second, Now, TimeSerial, TimeValue
input/outputInputBox, MsgBox
mathAtn, Cos, Sin, Tan, Exp, Log, Sqr, Randomize, Rnd
objectsIsObject
stringsAsc, AscB, AscW, Chr, ChrB, ChrW, Instr, InStrB, Len, LenB, LCase, UCase, Left, LeftB, Mid, MidB, Right, RightB, Space, StrComp,String, LTrim, RTrim, Trim
variantsIsArray, IsDate, IsEmpty, IsNull, IsNumeric, IsObject, VarType

VB Script and Web Browsers

The most important things you will be doing with your VB Scripts are interacting with the content and information on your Web pages, and through them with your user. Above, you have seen a little of one thing VB Script can do to your Web page-use document.write() to place information on the page itself.

VB Script interacts with your Web browser through the browser's object model. Different aspects of the Web browser exist as different objects, with properties and methods that can be accessed by VB Script. For instance, document.write() uses the write method of the document object. Understanding this Web browser object model is crucial to using VB Script effectively. Also, understanding how the Web browser processes and executes your scripts is also necessary.

When Scripts Execute

When you put VB Script code in a page, the Web browser evaluates the code as soon as it's encountered. Functions, however, don't get executed when they're evaluated; they just get stored for later use. You still have to call functions explicitly to make them work. Some functions are attached to objects, like buttons or text fields on forms, and they are called when some event happens on the button or field. You might also have functions that you want to execute during page evaluation. You can do so by putting a call to the function at the appropriate place in the page.

Where to Put Your Scripts

You can put scripts anywhere within your HTML page, as long as they're surrounded with the <SCRIPT>...</SCRIPT> tags. One good system is to put functions that will be executed more than once into the <HEAD> element of their pages; this element provides a convenient storage place. Since the <HEAD> element is at the beginning of the file, functions and VB Script code that you put there will be evaluated before the rest of the document is loaded. Then you can execute the function at the appropriate point in your Web page by calling it, as in:

<SCRIPT language="VBS">
<!-- Hide this script from incompatible Web browsers!
myFunction()
<!-- -->
</SCRIPT>

Another way to execute scripts is to attach them to HTML elements that support scripts. When scripts are matched with events attached to these elements, the script is executed when the event occurs. This can be done with HTML elements, such as forms, buttons, or links. Consider Listing 48.2, which shows a very simple example of attaching a VB Script function to the onClick attribute of an HTML forms button (see Figure 48.2).

Figure 48.2 : VB Script functions can be attached to form fields through several different methods.


Listing 48.2  Button1.htm-Calling a VB Script Function with the Click of a Button
<HTML>
<HEAD>
<SCRIPT LANGUAGE="VBS">
<!-- Hide this script from incompatible Web browsers!
sub Pressed
    alert "Stop that!"
end sub     
<!-- -->
</SCRIPT>
<TITLE>VB Scripts Attached to HTML Elements</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
<FORM NAME="Form1">
<INPUT TYPE="BUTTON" NAME="Button1" VALUE="Don't Press Me!"
        onClick="Pressed">
</FORM>
</BODY>
</HTML>

VB Script also provides you with several alternate ways to attach functions to objects and their events. The first is through the VB Script function name. To have a VB Script function execute when a given event occurs to an object, name the function object_event. For instance, Listing 48.3 shows an alternate way of coding Listing 48.2 using this method. Another method for simple actions is to attach the VB Script directly to the attribute of the HTML form element, as shown in Listing 48.4. All three of these listings will produce the output shown in Figure 48.2.


Listing 48.3  Button2.htm-VB Script Functions can be Named to be Called Automatically
<HTML>
<HEAD>
<SCRIPT LANGUAGE="VBS">
<!-- Hide this script from incompatible Web browsers!
sub Button1_onClick
    alert "Stop that!"
end sub     
<!-- -->
</SCRIPT>
<TITLE>VB Scripts Attached to HTML Elements</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
<FORM NAME="Form1">
<INPUT TYPE="BUTTON" NAME="Button1" VALUE="Don't Press Me!">
</FORM>
</BODY>
</HTML>


Listing 48.4  Button3.htm-Simple VB Scripts can be Attached Right to a Form Element
<HTML>
<HEAD>
<TITLE>VB Scripts Attached to HTML Elements</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
<FORM NAME="Form1">
    <INPUT TYPE="BUTTON" NAME="Button1" VALUE="Don't Press Me!"
        onClick="alert('I said Don\'t Press Me!')">
</FORM>
</BODY>
</HTML>

Sometimes, though, you have code that shouldn't be evaluated or executed until after all the page's HTML has been parsed and displayed. An example is a function to print out all the URLs referenced in a page. If this function is evaluated before all the HTML on the page has been loaded, it misses some URLs. Therefore, the call to the function should come at the page's end. The function itself can be defined anywhere in the HTML document; it is the function call that should be at the end of the page.

NOTE
VB Script code to modify the actual HTML contents of a document (as opposed to merely changing the text in a form text input field, for instance) must be executed during page evaluation.

Web Browser Objects and Events

In addition to recognizing VB Script when it's embedded inside a <SCRIPT>...</SCRIPT> tag, Internet Explorer 3 and other compatible browsers will also expose some objects, along with their methods and properties, that you can then use in your programs. The Web browsers can also trigger methods you define in response to events that are triggered when the user takes certain actions in the browser (for example, when a button is clicked). The examples shown in Listings 48.2, 48.3, and 48.4, all demonstrate this-a VB Script function is executed when a Web browser object (the form input field named Button1) responds to the onClick event (triggered by the user clicking the button).

Web Browser Object Hierarchy and Scoping

Figure 48.3 shows the page on the Microsoft Web site that gives the hierarchy of objects that the Web browser provides and that are accessible to VB Script. As shown, Window is the topmost object in the hierarchy, and the other objects are organized underneath it, as shown. The dashed lines show where more than one object of the given type can exist. Using this hierarchy, the full reference for the value of a text field named Text1 in an HTML form named Form1 would be Window.Document.Form1.Text1.Value.

Figure 48.3 : Objects defined by the Web browser are organized in a hierarchy and can be accessed and manipulated by VB Script.


ON THE WEB
http://www.microsoft.com/intdev/sdk/docs/scriptom/  for complete specifications for Microsoft's implementation of the Web browser object model.

However, because of the object scoping rules in VB Script, it is not necessary to specify this full reference. Scoping refers to the range over which a variable, function, or object is defined. For instance, a variable defined within a VB Script function is only scoped within that function-it cannot be referenced outside of the function. VB Scripts are scoped to the current window but not to the objects below the window in the hierarchy. So, for the preceding example, the text field value could also be referenced as Document.Form1.Text1.Value.

Web Browser Object Model

Many events that happen in a browsing session aren't related to items on the page (like buttons or HTML text). Instead, they're related to what's happening in the browser itself, like what page the user is viewing.

CAUTION
Remember that VB Script is a new language and support for it under Internet Explorer 3 and other Web browsers is also very new. As a result, the specifications of the language may change, as well as the objects, properties, methods, and events supplied by the Web browsers. Up-to-date information about the language can be found through Microsoft's VB Script Web site at http://www.microsoft.com/vbscript/, and information about the Web browser object models can be found through the Netscape Navigator and Microsoft Internet Explorer Web site.

The current definition of the Web browser object models defined by Netscape and Microsoft can be found on the CD-ROMs that accompany this book. In this section, you will get an overview of the most important objects, properties, methods, and events that are available-the ones you are most likely to use-and see some examples of their use.

The Location Object  The Web browser exposes an object called Location, which holds the current URL, including the hostname, path, CGI script arguments, and even the protocol. Table 48.4 shows some of the properties of the Location object.

Table 48.4  The Location Object Contains Information on the Currently Displayed URL

PropertyWhat It Contains
hrefThe entire URL, including all the subparts; for example, http://www.msn.com/products/msprod.htm
protocolThe protocol field of the URL, including the first colon; for example, http:
hostThe hostname and port number; for example, www.msn.com:80
hostnameThe hostname; for example, www.msn.com
portThe port, if specified; otherwise, it's blank
pathnameThe path to the actual document; for example, products/msprod.htm
hashAny CGI arguments after the first # in the URL
searchAny CGI arguments after the first ? in the URL

NOTE
Remember that VB Script is not case-sensitive, so, for example, references to the following are all equivalent:
Location.HREF
location.href
location.Href
LoCaTiOn.HrEf

Listing 48.5 shows an example of how you access and use the Location object. First, the current values of the Location properties are displayed on the Web page (see Figure 48.4). As you can see, not all of them are defined. Additionally, when the button is clicked, the Location. Href property is set to the URL of my home page. This causes the Web browser to load that page (see Figure 48.5).

Figure 48.4 : Manipulating the Location object gives you another means of moving from one Web page to another.

Figure 48.5 : By setting its Href property, you can use the Location object to change the URL your Web browser is looking at.


Listing 48.5  Location.htm-The Location Object Allows You to Access and Set Information About the Current URL
<HTML>
<HEAD>
<SCRIPT LANGUAGE="VBS">
<!-- Hide this script from incompatible Web browsers!
sub Button1_onClick
    Location.Href = "http://www.rpi.edu/ ~odonnj/"
end sub     
<!-- -->
</SCRIPT>
<TITLE>The Location Object</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
<SCRIPT LANGUAGE="VBS">
<!-- Hide this script from incompatible Web browsers!
document.write "Current Location information: <BR> <HR>"
document.write "Location.Href = " & Location.Href & "<BR>"
document.write "Location.Protocol = " & Location.Protocol & "<BR>"
document.write "Location.Host = " & Location.Host & "<BR>"
document.write "Location.Hostname = " & Location.Hostname & "<BR>"
document.write "Location.Port = " & Location.Port & "<BR>"
document.write "Location.Pathname = " & Location.Pathname & "<BR>"
document.write "Location.Hash = " & Location.Hash & "<BR>"
document.write "Location.Search = " & Location.Search & "<BR> <HR>"
<!-- -->
</SCRIPT>
<FORM NAME="Form1">
    <INPUT TYPE="BUTTON" NAME="Button1" VALUE="Goto JOD's Home Page!">
</FORM>
</BODY>
</HTML>

The Document Object  The Document object, as you might expect, exposes useful properties and methods of the active document. Location refers only to the URL of the active document, but Document refers to the document itself. Table 48.5 shows Document's properties and methods.

Table 48.5  The Document Object Containing Information on the CurrentlyLoaded and Displayed HTML Page

PropertyWhat It Contains
title Title of the current page, or Untitled if no title exists
locationThe document's address (read-only)
lastModifiedThe page's last-modified date
formsArray of all the FORMs in the current page
linksArray of all the HREF anchors in the current page
anchorsArray of all the anchors in the current page
linkColorLink color
alinkColorLink color
vlinkColorVisited link color
bgColorBackground color
fgColorForeground color
MethodWhat it does
writeWrites HTML to the current page

Listing 48.6 shows a VB Script that accesses and displays some of the properties of the Document object. Notice that the Links property is an array, one for each URL link on the current Web page. Figure 48.6 shows the results of loading this Web page.

Figure 48.6 : Document object properties contain information about the current document displayed in the Web browser.


Listing 48.6  Document.htm-The Document Object Allows You to Access and Set Information About the Current Document
<HTML>
<HEAD>
<TITLE>The Document Object</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
<A HREF="http://www.rpi.edu/ ~odonnj/">JOD's Home Page</A>
<A HREF="http://www.rpi.edu/ ~odonnj/Location.htm">The Location Object</A>
<HR>
<SCRIPT LANGUAGE="VBS">
<!-- Hide this script from incompatible Web browsers!
Dim n
document.write "Current Document information: <BR> <HR>"
document.write "Document.Title = " & Document.Title & "<BR>"
document.write "Document.Location = " & Document.Location & "<BR>"
document.write "Document.lastModified = " & Document.lastModified & "<BR>"
for n = 0 to Document.Links.Length-1
   document.write "Document.Links(" & Cstr(n) & ").Href = " & _
      Document.Links(n).Href & "<BR>"
next
document.write "Document.linkColor = " & Document.linkColor & "<BR>"
document.write "Document.alinkColor = " & Document.alinkColor & "<BR>"
document.write "Document.vlinkColor = " & Document.vlinkColor & "<BR>"
document.write "Document.bgColor = " & Document.bgColor & "<BR>"
document.write "Document.fgColor = " & Document.fgColor & "<BR> <HR>"
<!-- -->
</SCRIPT>
</BODY>
</HTML>

Some of the real power of the Document object, however, is realized by making use of the objects underneath it in the hierarchy; particularly the different HTML forms elements available. This is because these elements are the primary ways of interacting with the user of a Web page.

The Form Object

The HTML form object is the primary way for Web pages to solicit different types of input from the user. VB Script will often work along with HTML forms in order to perform its functions. The object model for HTML forms includes a wide variety of properties, methods, and events that can be used to program VB Scripts.

Form Methods and Events  Table 48.6 shows some of the methods and events attached to HTML form objects. The methods and events can be used in VB Scripts-the methods can be used to perform certain functions, and the events can be used to trigger VB Script functions. For instance, if there is a text area named Text1 as part of a form named Form1, the method Document.Form1.Text1.Focus() can be called in a VB Script to force the focus to move to that text area. On the other hand, if there is a button named Button1 in the same form, the event onClick can be used as an attribute to the <INPUT> tag to call a VB Script function when the button is clicked (an example of the different ways of doing this was shown in Listings 48.2, 48.3, and 48.4).

Table 48.6  Methods and Events that Allow You to Control the Contents and Behavior of HTML Elements

MethodWhat It Does
focus()Calls to move the input focus to the specified object.
blur()Calls to move the input focus away from the specified object.
select()Calls to select the specified object.
click()Calls to click the specified object, which must be a button.
EventWhen It Occurs
onFocusWhen the user moves the input focus to the field, either via the Tab key or a mouse click.
onBlurWhen the user moves the input focus out of this field.
onSelectWhen the user selects text in the field.
onChange Only when the field loses focus and the user has modified its text; use this function to validate data in a field.
onSubmitWhen the user submits the form (if the form has a Submit button).
onClickWhen the button is clicked.

Note that focus(), blur(), select(), and click() are methods of objects; to call them, you use the name of the object you want to affect. For example, to turn off the button named Search, you type Document.Form.Search.Disable().

In addition to the methods and events, form objects have properties that can be used by VB Scripts. Table 48.7 lists the properties exposed for HTML form elements.

Table 48.7  HTML Forms Properties that You Can Use in Your VB Script Code

PropertyWhat It Contains
nameThe value of the form's NAME attribute.
methodThe value of the form's METHOD attribute.
actionThe value of the form's ACTION attribute.
elementsThe elements array of the form.
encodingThe value of the form's ENCODING attribute.
targetWindow targeted after submit for form response.
MethodWhat It Does
submit()Any form element can force the form to be submitted by calling the form's submit() method.
EventWhen It Occurs
onSubmit()When the form is submitted; this method can't stop the submission, though.

Properties for Objects in a Form  A good place to use VB Script is in forms, since you can write scripts that process, check, and perform calculations with the data the user enters. VB Script provides a useful set of properties and methods for text INPUT elements and buttons.

You use INPUT elements in a form to let the user enter text data; VB Script provides properties to get the objects that hold the element's contents, as well as methods for doing something when the user moves into or out of a field. Table 48.8 shows the properties and methods that are defined for text INPUT elements.

Table 48.8  Properties and Methods that Allow You to Control the Contents and Behavior of HTML INPUT Elements

PropertyWhat It Contains
nameThe value of the element's NAME attribute.
valueThe field's contents.
defaultValueThe initial contents of the field; returns "" if blank.
MethodWhat It Does
onFocusCalled when the user moves the input focus to the field, either via the Tab key or a mouse click.
onBlurCalled when the user moves the input focus out of this field.
onSelectCalled when the user selects text in the field.
onChange Called only when the field loses focus and the user has modified its text; use this action to validate data in a field.

Individual buttons and check boxes have properties, too; VB Script provides properties to get objects containing a button's data, as well as methods for doing something when the user selects or deselects a particular button. Table 48.9 shows some of the properties and methods that are defined for button elements.

Table 48.9  Properties and Methods that Allow You to Control the Contents and Behavior of HTML Button and Check Box Elements

PropertyWhat It Contains
nameThe value of the button's NAME attribute
valueThe VALUE attribute
checkedThe state of a check box
defaultCheckedThe initial state of a check box
MethodWhat It Does
click()Clicks a button and triggers whatever actions are attached to it
EventWhen It Occurs
onClickCalled when the button is pressed

As an example of what you can do with VB Script and the objects, properties, and methods outlined, you might want to put the user's cursor into the first text field in a form automatically, instead of making the user manually click the field. If your first text field is named UserName, you can put the following in your document's script to get the behavior you want:

Document.Form.UserName.Focus()

An example of using VB Script with HTML forms is shown in the later "VB Script Intranet Application" section.

Example VB Script Applications

As with most programming languages, you can learn best by doing, and the easiest way to "do" is to take a look at some examples. The listings shown so far have demonstrated some of the things you can do with VB Script. Below are two more examples, giving some more practical examples of VB Script in action.

VB Script Intranet Application

Unless and until VB Script becomes more widespread on the Internet, its best applications might be intranet applications, in companies or organizations that have adopted Microsoft Internet Explorer as their standard. In order to show some of the capabilities of VB Script and the kind of applications it can be used for, I will lead you through the design of an HTML form and VB Script for submitting a timesheet.

In my organization, we are required to fill out a timesheet every other week, detailing how many hours we have worked each day on each of our projects. There are several guidelines that we have to follow when working and when filling out our timesheets: We have to account for eight hours a day of work or leave, and hours worked in excess of eight hours a day are considered overtime.

The goal of designing a Web page for the submission of a timesheet is to decrease the amount of paper flying around our office. Normally, we filled out a timesheet that was initialed by our group leader and then used by the secretary to fill out a timecard. By putting the timesheet on the computer, we save a little time and paper.

Designing the HTML Form  The first step in the process is designing the HTML form for the timesheet. This is pretty simple. We will use one form for the employee information and for the timesheet itself. The part of the form for the employee information is very straightforward and the HTML to generate it looks like this:

<FORM NAME="TS" ACTION="mailto:odonnj@rpi.edu" METHOD=POST>
<TABLE BORDER>
<TR><TD ALIGN=RIGHT BGCOLOR=CYAN><B>EMPLOYEE NAME</B></TD>
    <TD BGCOLOR=YELLOW>
        <INPUT NAME="EmpName" TYPE="Text" VALUE="" SIZE=40 ></TD></TR>
<TR><TD ALIGN=RIGHT BGCOLOR=CYAN><B>ID NUMBER</B></TD>
    <TD BGCOLOR=YELLOW>
        <INPUT NAME="IDNum" TYPE="Text" VALUE="" SIZE=40 ></TD></TR>
</TABLE>
<TABLE BORDER>

This is used by the employees to enter their names and ID numbers. An HTML table is used to lay out the form and a little color is added for appearance. We are careful to assign names to the form and to the two input fields, as they will be used by VB Script to reference those elements.

The timesheet part of the form is also pretty straightforward, although there is a lot more HTML code involved. Each line of the timesheet form requires 18 text fields, one each for the 14 days of the pay period, two for weekly totals, one for the pay period total, and one for the job order number of the project (or the numeric code for annual or sick leave). The top of this part of the form, showing the column headings and the first row of the timesheet, looks like:

<TR BGCOLOR=CYAN>
    <TH>Job Order Number</TH>
    <TH>SU</TH>
    <TH>MO</TH><TH>TU</TH><TH>WE</TH><TH>TH</TH><TH>FR</TH>
    <TH>SA</TH><TH>Week #1</TH>
    <TH>SU</TH>
    <TH>MO</TH><TH>TU</TH><TH>WE</TH><TH>TH</TH><TH>FR</TH>
    <TH>SA</TH><TH>Week #2</TH><TH>Pay Period</TH></TR>
<TR ALIGN=CENTER>
    <TD BGCOLOR=YELLOW><INPUT TYPE="Text" VALUE="" SIZE=16></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD></TR>
    [etc...]

NOTE
Don't worry, the complete listing for this VB Script application will be shown a little later, and also appears on the CD-ROMs.

You might notice a few things about the fields in this form that are different than the fields in the first form. First, the different fields are not named. If we name each field separately, the VB Script functions to process them would be very repetitive-after all, we will be doing the same operations on each row in the form. So, rather than naming the fields, we make use of the Elements property of the Form object. Elements is an array of the fields in the Form object in the order they are originally defined. So, for the first row of the form shown above, the fields shown can be references with Document.Timesheet.Elements(0) through Document.Timesheet.Elements(17).

The second thing different about this form is that most of the fields set the onChange attribute of the <INPUT> tag to call the VB Script function Calc. We will discuss what this does in the next section.

So, with a total of five rows for the timesheet, and additional rows for annual leave, sick leave, and overtime, we have our HTML document for a timesheet. The resulting Web page looks like Figure 48.7. (The Submit Timesheet button and text field beside it will be explained later in this chapter.)

Figure 48.7 : Using a combination of HTML forms and tables, setting up this timesheet is simple.

Adding VB Scripts  At this point, we could be done, and the employees filling out our Web page timesheet wouldn't be any worse off than when filling out the paper version. They could enter their name, ID number, job order number, hours worked, and total hours for the week and the pay period.

But, we can use VB Script to perform some of these calculations automatically. As shown in Figure 48.7, each form field in the Timesheet form (other than the ones for the job order number) has the VB Script function Calc attached to its onChange event. That means every time that form field changes value, Calc is called. Here is the VB Script for Calc:

Sub Calc
   Dim i,j,jmax,sum
   jmax = 7
   For k = 0 to 1
      For i = 0 to 6
         sum = 0
         For j = 0 to jmax-1
            If (IsNumeric(Document.TS.Elements(k*8+j*18+i+3).Value)) Then
               sum = sum + CDbl(Document.TS.Elements(k*8+j*18+i+3).Value)
            End If
         Next
         If (sum > 8 Or (sum > 0 And (i = 0 Or i = 6))) Then
            If (i = 0 Or i = 6) Then
               Document.TS.Elements(k*8+jmax*18+i+3).Value = sum
            Else
               Document.TS.Elements(k*8+jmax*18+i+3).Value = sum - 8
            End If
         Else
            Document.TS.Elements(k*8+jmax*18+i+3).Value = ""
         End If
      Next
   Next
   For j = 0 to jmax
      Document.TS.Elements(j*18+10).Value = 0
      Document.TS.Elements(j*18+18).Value = 0
      For i = 0 to 6
         If (IsNumeric(Document.TS.Elements(j*18+i+3).Value)) Then
            Document.TS.Elements(j*18+10).Value = _
               CDbl(Document.TS.Elements(j*18+10).Value) + _
               CDbl(Document.TS.Elements(j*18+i+3).Value)
         End If
         If (IsNumeric(Document.TS.Elements(j*18+i+11).Value)) Then
            Document.TS.Elements(j*18+18).Value = _
               CDbl(Document.TS.Elements(j*18+18).Value) + _
               CDbl(Document.TS.Elements(j*18+i+11).Value)
         End If
      Next
      Document.TS.Elements(j*18+19).Value = _
         CDbl(Document.TS.Elements(j*18+10).Value) + _
         CDbl(Document.TS.Elements(j*18+18).Value)
   Next
   Document.TS.Elements((jmax-2)*18+2).Value = "SICK LEAVE"
   Document.TS.Elements((jmax-1)*18+2).Value = "ANNUAL LEAVE"
   Document.TS.Elements(jmax*18+2).Value = "OVERTIME"
End Sub

Now, this looks trickier than it really is, so we'll go through it step by step. The first two lines

Dim i,j,jmax,sum
jmax = 7

set up some local variables and set jmax to the number of timesheet rows.

Next, there are two sets of nested For...Next loops to perform the calculations that we are interested in. The first set is used to add up each column of the timesheet, to see if there were any overtime hours worked-overtime defined as any hours over eight worked on a weekday or any hours worked at all on a weekend. After this number is calculated, each cell in the overtime row is set appropriately.

The next set of For...Next loops allows us to process each row in the timesheet, including the "extra" row used for overtime, and total up the hours for that row. The two lines

X.Elements(j*18+10).Value = 0
X.Elements(j*18+18).Value = 0

initialize the form elements for the weekly totals to zero. The inner For...Next adds up and sets each row's totals. The section of code that does this looks like

If (IsNumeric(Document.TS.Elements(j*18+i+3).Value)) Then
   Document.TS.Elements(j*18+10).Value = _
      CDbl(Document.TS.Elements(j*18+10).Value) + _
      CDbl(Document.TS.Elements(j*18+i+3).Value)
End If
If (IsNumeric(Document.TS.Elements(j*18+i+11).Value)) Then
   Document.TS.Elements(j*18+18).Value = _
      CDbl(Document.TS.Elements(j*18+18).Value) + _
      CDbl(Document.TS.Elements(j*18+i+11).Value)
End If

This code does the following:

  1. Determines if there is a number entered into the field.
  2. Adds the number of hours worked to the total for that row.

This is done for each week, and then the last two lines in this For...Next loop add the two weekly totals to get the total for the pay period. The last thing performed by the function is to make sure the job order number field of the annual leave, sick leave, and overtime rows are set equal to their correct values.

With this VB Script attached to the form fields of the timesheet, completing the sheet becomes a bit easier (see Figure. 48.8). Weekly and pay period totals are calculated automatically each time you enter a number and move the cursor. Overtime hours will be added automatically when more than eight hours a day are worked. Obviously, the script could be made smarter-verifying that the correct number of hours per pay period are worked, for instance-but this is a good start.

Figure 48.8 : VB Scripts automatically update the weekly and pay period totals whenever new information is entered into the timesheet.

Adding Memory with Cookies  There's one more thing that this Web page could use, something that we do have with paper timesheets. With paper timesheets, each employee received a timesheet with their name, ID number, and the job order numbers of the most common projects they worked on, already printed on it. One way we could do this would be to create a separate Web page for each employee. There is a better way, however, that requires only one Web page and stores the personal information on each employee's local computer. This can be done using cookies.

In this example, we will need seven cookies, one each for the employee name and ID number, and one each for the five job order numbers. Creating or changing a cookie is very simple and is included in the VB Script function that is called when the Submit Timesheet button is clicked:

Sub SubmitTS_onClick
   Document.Cookie = "EmpName=" & Document.TS.EmpName.Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.Cookie = "IDNum=" & Document.TS.IDNum.Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.Cookie = "JON1=" & Document.TS.Elements(2).Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.Cookie = "JON2=" & Document.TS.Elements(20).Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.Cookie = "JON3=" & Document.TS.Elements(38).Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.Cookie = "JON4=" & Document.TS.Elements(56).Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.Cookie = "JON5=" & Document.TS.Elements(74).Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.TS.CookieTS.Value = Document.Cookie
   Document.TS.Submit
   MsgBox "Timesheet Submitted!"
End Sub

This function saves each of the seven cookies, displays the cookie in the long text field at the bottom of the timesheet (this isn't necessary, of course, but is helpful for this example), submits the form, and pops up a message box to tell the user that the form has been submitted (see Figure 48.9).

Figure 48.9 : A VB Script message box is used to tell the user that the timesheet has been submitted.

Once the cookie has been saved, whenever that Web page is loaded, the cookie will be available. It is still necessary to get the information out of the cookie and into the appropriate text fields. We use a VB Script (located at the bottom of the HTML document so that it executes after the rest of the page has been loaded) to search the cookie and put the appropriate information in each of the text fields:

<SCRIPT LANGUAGE="VBS">
<!-- Hide this script from incompatible Web browsers!
Document.TS.EmpName.Value = GetCookie("EmpName")
Document.TS.IDNum.Value = GetCookie("IDNum")
Document.TS.Elements(2).Value = GetCookie("JON1")
Document.TS.Elements(20).Value = GetCookie("JON2")
Document.TS.Elements(38).Value = GetCookie("JON3")
Document.TS.Elements(56).Value = GetCookie("JON4")
Document.TS.Elements(74).Value = GetCookie("JON5")
Document.TS.CookieTS.Value = Document.Cookie
<!-- -->
</SCRIPT>

The VB Script function GetCookie is used to search the cookie for each piece of it. A document cookie is essentially a long string with each piece included as CookieName=Value, and separated from the next field by a semicolon. GetCookie uses VB Script string manipulation functions to search through the document cookie for a given piece and either returns its value, if defined, or an empty string.

Function GetCookie(CookieName)
   Dim Loc
   Dim NamLen
   Dim ValLen
   Dim LocNext
   Dim Temp

   NamLen = Len(CookieName)
   Loc = Instr(Document.Cookie, CookieName)

   If Loc = 0 Then
      GetCookie = ""
   Else
      Temp = Right(Document.Cookie, Len(Document.Cookie) - Loc + 1)
      If Mid(Temp, NamLen + 1, 1) <> "=" Then
         GetCookie = ""
      Else
         LocNext = Instr(Temp, ";")
         If LocNext = 0 Then LocNext = Len(Temp) + 1
         If LocNext = (NamLen + 2) Then
            GetCookie = ""
         Else
            ValLen = LocNext - NamLen - 2
            GetCookie = Mid(Temp, NamLen + 2, ValLen)
         End If
      End If
   End if
End Function

With this in place, the next time the Web page is loaded, the employee name, ID number, and job order numbers used on the last submitted timesheet are filled in automatically. In our example, the document cookie is also displayed in the lower text field (see Figure 48.10).

Figure 48.10 : Using cookies allows a single Web page to serve multiple users, customizing it with their particular information.

The VB Script Timesheet Web Page  The complete listing for the VB Script Web page is shown in Listing 48.7. As mentioned previously, the VB Script can be made a lot smarter and the form can be customized pretty easily to add more timesheet rows or to include a dedicated annual or sick leave row.


Listing 48.7  Timesheet.htm-VB Script Can Be Used to Automate Many User Input Functions
<HTML>
<HEAD>
<SCRIPT LANGUAGE="VBS">
<!-- Hide this script from incompatible Web browsers!
Sub Calc
   Dim i,j,jmax,sum
   jmax = 7
   For k = 0 to 1
      For i = 0 to 6
         sum = 0
         For j = 0 to jmax-1
            If (IsNumeric(Document.TS.Elements(k*8+j*18+i+3).Value)) Then
               sum = sum + CDbl(Document.TS.Elements(k*8+j*18+i+3).Value)
            End If
         Next
         If (sum > 8 Or (sum > 0 And (i = 0 Or i = 6))) Then
            If (i = 0 Or i = 6) Then
               Document.TS.Elements(k*8+jmax*18+i+3).Value = sum
            Else
               Document.TS.Elements(k*8+jmax*18+i+3).Value = sum - 8
            End If
         Else
            Document.TS.Elements(k*8+jmax*18+i+3).Value = ""
         End If
      Next
   Next
   For j = 0 to jmax
      Document.TS.Elements(j*18+10).Value = 0
      Document.TS.Elements(j*18+18).Value = 0
      For i = 0 to 6
         If (IsNumeric(Document.TS.Elements(j*18+i+3).Value)) Then
            Document.TS.Elements(j*18+10).Value = _
               CDbl(Document.TS.Elements(j*18+10).Value) + _
               CDbl(Document.TS.Elements(j*18+i+3).Value)
         End If
         If (IsNumeric(Document.TS.Elements(j*18+i+11).Value)) Then
            Document.TS.Elements(j*18+18).Value = _
               CDbl(Document.TS.Elements(j*18+18).Value) + _
               CDbl(Document.TS.Elements(j*18+i+11).Value)
         End If
      Next
      Document.TS.Elements(j*18+19).Value = _
         CDbl(Document.TS.Elements(j*18+10).Value) + _
         CDbl(Document.TS.Elements(j*18+18).Value)
   Next
   Document.TS.Elements((jmax-2)*18+2).Value = "SICK LEAVE"
   Document.TS.Elements((jmax-1)*18+2).Value = "ANNUAL LEAVE"
   Document.TS.Elements(jmax*18+2).Value = "OVERTIME"
End Sub

Function GetCookie(CookieName)
   Dim Loc
   Dim NamLen
   Dim ValLen
   Dim LocNext
   Dim Temp

   NamLen = Len(CookieName)
   Loc = Instr(Document.Cookie, CookieName)
	
   If Loc = 0 Then
      GetCookie = ""
   Else
      Temp = Right(Document.Cookie, Len(Document.Cookie) - Loc + 1)
      If Mid(Temp, NamLen + 1, 1) <> "=" Then
         GetCookie = ""
      Else
         LocNext = Instr(Temp, ";")
         If LocNext = 0 Then LocNext = Len(Temp) + 1
         If LocNext = (NamLen + 2) Then
            GetCookie = ""
         Else
            ValLen = LocNext - NamLen - 2
            GetCookie = Mid(Temp, NamLen + 2, ValLen)
         End If
      End If
   End if
End Function

Sub SubmitTS_onClick
   Document.Cookie = "EmpName=" & Document.TS.EmpName.Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.Cookie = "IDNum=" & Document.TS.IDNum.Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.Cookie = "JON1=" & Document.TS.Elements(2).Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.Cookie = "JON2=" & Document.TS.Elements(20).Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.Cookie = "JON3=" & Document.TS.Elements(38).Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.Cookie = "JON4=" & Document.TS.Elements(56).Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.Cookie = "JON5=" & Document.TS.Elements(74).Value & _
      ";expires=31-Dec-99 12:00:00 GMT"
   Document.TS.CookieTS.Value = Document.Cookie
   Document.TS.Submit
   MsgBox "Timesheet Submitted!"
End Sub
<!-- -->
</SCRIPT>
<TITLE>VB SCRIPT TIMESHEET</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
<FORM NAME="TS" ACTION="mailto:odonnj@rpi.edu" METHOD=POST>
<TABLE BORDER>
<TR><TD ALIGN=RIGHT BGCOLOR=CYAN><B>EMPLOYEE NAME</B></TD>
    <TD BGCOLOR=YELLOW>
        <INPUT NAME="EmpName" TYPE="Text" VALUE="" SIZE=40 ></TD></TR>
<TR><TD ALIGN=RIGHT BGCOLOR=CYAN><B>ID NUMBER</B></TD>
    <TD BGCOLOR=YELLOW>
        <INPUT NAME="IDNum" TYPE="Text" VALUE="" SIZE=40 ></TD></TR>
</TABLE>
<TABLE BORDER>
<TR BGCOLOR=CYAN>
    <TH>Job Order Number</TH>
    <TH>SU</TH>
    <TH>MO</TH><TH>TU</TH><TH>WE</TH><TH>TH</TH><TH>FR</TH>
    <TH>SA</TH><TH>Week #1</TH>
    <TH>SU</TH>
    <TH>MO</TH><TH>TU</TH><TH>WE</TH><TH>TH</TH><TH>FR</TH>
    <TH>SA</TH><TH>Week #2</TH><TH>Pay Period</TH></TR>
<TR ALIGN=CENTER>
    <TD BGCOLOR=YELLOW><INPUT TYPE="Text" VALUE="" SIZE=16></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD></TR>
<TR ALIGN=CENTER>
    <TD BGCOLOR=YELLOW><INPUT TYPE="Text" VALUE="" SIZE=16></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD></TR>
<TR ALIGN=CENTER>
    <TD BGCOLOR=YELLOW><INPUT TYPE="Text" VALUE="" SIZE=16></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD></TR>
<TR ALIGN=CENTER>
    <TD BGCOLOR=YELLOW><INPUT TYPE="Text" VALUE="" SIZE=16></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD></TR>
<TR ALIGN=CENTER>
    <TD BGCOLOR=YELLOW><INPUT TYPE="Text" VALUE="" SIZE=16></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD></TR>
<TR ALIGN=CENTER>
    <TD BGCOLOR=RED>
       <INPUT TYPE="Text" VALUE="SICK LEAVE" SIZE=16 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD></TR>
<TR ALIGN=CENTER>
    <TD BGCOLOR=RED>
       <INPUT TYPE="Text" VALUE="ANNUAL LEAVE" SIZE=16
           onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD BGCOLOR=RED>
        <INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD></TR>
<TR ALIGN=CENTER BGCOLOR=RED>
    <TD><INPUT TYPE="Text" VALUE="OVERTIME" SIZE=16 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="" SIZE=1 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD>
    <TD><INPUT TYPE="Text" VALUE="0" SIZE=2 onChange="Calc"></TD></TR>
<!--<TR><TD BGCOLOR=CYAN COLSPAN=18>&nbsp</TD></TR>-->
<TR ALIGN=CENTER>
    <TD><INPUT NAME="SubmitTS" TYPE="Button"
            VALUE="Submit Timesheet"></TD>
    <TD COLSPAN=17 BGCOLOR=RED>
        <INPUT NAME="CookieTS" TYPE="Text" SIZE="110"></TD></TR>
</TABLE>
</FORM>
<SCRIPT LANGUAGE="VBS">
<!-- Hide this script from incompatible Web browsers!
Document.TS.EmpName.Value = GetCookie("EmpName")
Document.TS.IDNum.Value = GetCookie("IDNum")
Document.TS.Elements(2).Value = GetCookie("JON1")
Document.TS.Elements(20).Value = GetCookie("JON2")
Document.TS.Elements(38).Value = GetCookie("JON3")
Document.TS.Elements(56).Value = GetCookie("JON4")
Document.TS.Elements(74).Value = GetCookie("JON5")
Document.TS.CookieTS.Value = Document.Cookie
<!-- -->
</SCRIPT>
</BODY>
</HTML>

CAUTION
The cookie storage mechanism that is part of this Web page does not always work when the Web page is viewed locally because cookies need to go through a Web server to be processed. Unless you are running a local server, you may need to upload the HTML document to your ISP's system and view it with their Web server to see the cookies work.

Of course, once the forms are submitted, what to do with them at the receiving end is another question, one for a different chapter.

Interacting with Objects

This is an example of using VB Script to manipulate another Web browser object-in this case, the ActiveX Label Control. The Label Control allows the Web author to place text on the Web page and select the text, font, size, and an arbitrary angle of rotation. One of the exciting things about the Label Control is that it can be manipulated in real time, producing a variety of automated or user-controlled effects.

In the following example, text is placed on the Web page using the Label Control, and form input is used to allow the user to change the text used and the angle at which it is displayed. Figure 48.11 shows the default configuration of the label, and Figure 48.12 shows it after the text and the rotation angle have been changed.

Figure 48.11 : The ActiveX Label Control allows arbitrary text to be displayed by the Web author in the size, font, position, and orientation desired.

Figure 48.12 : VB Script's ability to manipulate Web browser objects allows the label parameters to be changed dynamically.

Listing 48.8 shows the code used to produce this example. The following are some things to note about the example:

CAUTION
The example requires that you have the ActiveX Label Control on your system. Next chapter, you will learn how to get this control (if you don't have it) and also how to write Web pages that automatically download and install required components like the Label Control when they are not present on the client system.


Listing 48.8  Object.htm-VB Script Can Interact with Objects
<HTML>
<HEAD>
<OBJECT classid="clsid:99B42120-6EC7-11CF-A6C7-00AA00A47DD2"
        id=lblActiveLbl
        width=250
        height=250
        align=left
        hspace=20
        vspace=0
>
<PARAM NAME="Angle" VALUE="0">
<PARAM NAME="Alignment" VALUE="4">
<PARAM NAME="BackStyle" VALUE="0">
<PARAM NAME="Caption" VALUE="A Sample Label">
<PARAM NAME="FontName" VALUE="Arial">
<PARAM NAME="FontSize" VALUE="20">
<PARAM NAME="FontBold" VALUE="1">
<PARAM NAME="ForeColor" VALUE="0">
</OBJECT>
<SCRIPT LANGUAGE="VBS">
<!-- Hide this script from incompatible Web browsers
Sub cmdChangeIt_onClick
   Dim TheForm
   Set TheForm = Document.LabelControls
   lblActiveLbl.Caption = TheForm.txtNewText.Value
End Sub
Sub cmdRotateP_onClick
   Dim TheForm
   Set TheForm = Document.LabelControls
   lblActiveLbl.Angle = lblActiveLbl.Angle + 5
   Document.LabelControls.sngAngle.Value = lblActiveLbl.Angle
End Sub
Sub cmdRotateM_onClick
   Dim TheForm
   Set TheForm = Document.LabelControls
   lblActiveLbl.Angle = lblActiveLbl.Angle - 5
   Document.LabelControls.sngAngle.Value = lblActiveLbl.Angle
End Sub
<!-- -->
</SCRIPT>
<TITLE>VB Script and Object Manipulation</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF>
<FORM NAME="LabelControls">
<TABLE>
<TR><TD><INPUT TYPE="TEXT" NAME="txtNewText" SIZE=25></TD>
    <TD><INPUT TYPE="BUTTON" NAME="cmdChangeIt" VALUE="Change Text">
    </TD></TR>
<TR><TD><INPUT TYPE="TEXT" NAME="sngAngle" SIZE=5></TD>
    <TD><INPUT TYPE="BUTTON" NAME="cmdRotateP" VALUE="Rotate Label + 5">
    </TD></TR>
<TR><TD></TD>
    <TD><INPUT TYPE="BUTTON" NAME="cmdRotateM" VALUE="Rotate Label - 5">
    </TD></TR>
</TABLE>
</FORM>
<SCRIPT LANGUAGE="VBS">
<!-- Hide this script from incompatible Web browsers
Document.LabelControls.sngAngle.Value = lblActiveLbl.Angle
Document.LabelControls.txtNewText.Value = lblActiveLbl.Caption
<!-- -->
</SCRIPT>
</BODY>
</HTML>

Microsoft's JScript

With version 3 of their Internet Explorer Web browser, Microsoft has included JavaScript compatibility. However, what they have chosen to do is to create what they call JScript, which they describe as an open implementation of the JavaScript language.

Exactly what this means for Web page authors is unclear. Compatibility with the JavaScript language has been Microsoft's goal with JScript, but considering that JScript is currently a beta release of a scripting language striving for compatibility with a beta release of a different scripting language-JavaScript-there is likely to be many incompatibilities between the two. For Web authors interested in designing pages for the largest possible audience, testing JavaScript/JScript Web pages with both Netscape Navigator and Microsoft Internet Explorer seems like a good idea.

What Scripting Language Should You Use?

With a choice of scripting languages now available, the question of which to use quickly arises. JavaScript and VB Script have similar capabilities. Also, since they are both relatively new, you don't have a lot of history to rely on for making a choice. The following are a few points to consider: