Search the Catalog
Learning VBScript

Learning VBScript

By Paul Lomax
1st Edition July 1997
1-56592-247-6, Order Number: 2476
616 pages, $39.95, Includes CD-ROM

Chapter 1 Excerpt
What Can Be Achieved Using VBScript?

VBScript brings professional programming techniques to HTML web documents. With VBScript, we can create documents and applications that previously could only have been made available as a desktop program written with something like Visual Basic. It gives us the ability to interact with and manipulate HTML docu- ments directly from the browser. With VBScript, we can even interact with and manipulate the browser itself, sending it instructions from our VBScript program, and pulling in its variables for our own use. Let's look at a quick example of this. Figure 1-17 shows a web page that displays the date on which this particular HTML file was last modified, and also shows the referrer of this page, or the URL of the document whose hyperlink was followed to reach this page. As you are probably well aware, it is impossible to display either of these items of informa- tion with standard HTML (unless, of course, you "hardcode" them into your HTML document, in which case you're probably not really displaying the date the file was last modified or the hyperlink by which it was reached). Instead, HTML intermixed with VBScript was used to produce this page. You can see a portion of the very simple and straightforward source code responsible for producing it in Figure 1-18.

Figure 1-17: Using VBScript to get information from the browser

Above all, VBScript brings to us true client-side processing, so let's briefly look at some of the main uses of VBScript:

Figure 1-18: VBScript and HTML source code for the example in Figure 1-17

Reference and Manipulate Document Objects

Document objects, or, to give them their correct title, intrinsic HTML objects, are the display objects we currently use time and again in our HTML code, usually within the >INPUT< tag, to create forms. VBScript gives us the ability to access the properties of these objects (for example, to determine the value typed into an input text box by the user). Not only do we have access to these properties, we can also use VBScript to set the values of these properties. For example, we could set the value of an HTML text box to a particular value-perhaps to the current date and time on the client machine-as the page loads.

With normal HTML code, you can set the VALUE attribute of a text box just as easily. But unless you build your HTML source code from a script on the server (using an older technology like server-side includes, or a newer one like server-side VBScript with Active Server Pages), any value must be "hardcoded" into your HTML document. For instance, to continue with our date and time example, you could include the following line in your HTML document so that your web page displays the date and time:

<INPUT TYPE=text NAME=txtTime VALUE="2/3/97 12:01:00 PM">

But unless you update your page immediately before each user accesses it, the date and time displayed when a user's browser displays the page is going to become increasingly inaccurate. Rather than using hardcoded HTML, you could instead use CGI to transmit the current date and time to display on a client machine. This is, however, the time on the server machine, and not the time on the client machine; in some cases (on slow Internet connections, in periods of heavy traffic, and, of course, in cases where the Internet server is in a different time zone than the client), the web page ends up displaying a date and time that may be more or less inaccurate. And a basic problem is that, whether you hardcode the date and time into your HTML document or whether you generate it "dynamically" through a CGI application, once the page is displayed, the value of the date and time becomes fixed.

How does VBScript help with some simple task like displaying the date and time? VBScript not only supports the standard document objects, it also allows us to attach events to these objects. To put this another way, when the user or another part of our program interacts in some way with a particular object, like a command button, the browser can automatically run a particular routine within our program. For example, if the user clicks on a certain button or moves away from a text box, an "event" is fired that causes a particular routine to execute.

The HTML code in Example 1-1 illustrates how easy it is to display the current date and time on the client machine when the document is loaded. It also allows the user to update the date and time by pressing the Update Time button.

Example 1-1: Using VBScript to display the date and time

<HTML>
<HEAD>
<TITLE>Date/Time Example</TITLE>
</HEAD>
<BODY>
<CENTER>
<H3> Welcome to my Web page! </H3>
<FORM NAME="frmMyForm">
   <INPUT TYPE=text  NAME="timeinfo">
   <INPUT TYPE=button VALUE="Update Time" NAME="btnTime">
</FORM>
<SCRIPT LANGUAGE="vbscript">
    frmMyForm.timeinfo.value = Now
    Sub btnTime_OnClick
        frmMyForm.timeinfo.value = Now
    End Sub
</SCRIPT>
</BODY>
</HTML>

Reference and Manipulate the Browser

To VBScript, the browser itself is an object; in fact, it is several objects, all of which have properties. Using VBScript, you can control things such as the browser's history list and its status bar. You have tight control over how frames are handled within the browser window. You can check and reset the location or the URL, and automatically navigate to another page or even another web site. Let's say an application has one main document and two secondary documents, and that which of the two secondary documents you load depends on a combina- tion of responses from the user to the primary document (much more complex than simply clicking on a hyperlink). Automatically handling that decision process and retrieving the chosen document is an ideal job for VBScript. You can also call other VBScript programs in other frames and windows within the browser, and even open new browser windows at will, while controlling the appearance of the window at the same time. Chapter 5, Controlling the Browser, and Chapter 6, The Element Object and HTML Intrinsic Controls, provide an in-depth look at the objects exposed by the browser.

Example 1-2 contains a very simple script that controls the browser's status bar. When the user clicks the Click Me button, a VBScript routine generates a random number. If its value is less than .5, the text "Here's some text in the status bar" appears in the status bar; if its value is greater than .5, any text in the status bar is removed.

Example 1-2: Using VBScript to control the status bar

<HTML>
<HEAD>
<SCRIPT LANGUAGE="vbscript">
 Randomize
 Sub cmdButton1_OnClick
     dblNumber = Rnd()   
     If dblNumber <= .5 Then
        Status = "Here's some text in the status bar."
     Else
        Status = ""
     End If
 End Sub
</SCRIPT>
</HEAD>
<BODY BGCOLOR="white">
<CENTER>
<INPUT TYPE="button" NAME="cmdButton1" VALUE="Click Me">
</CENTER>
</BODY>
</HTML>

Reference the Contents of Another Loaded Document or Documents

Many of us use frames in our web pages and applications. Implemented correctly, frames enhance the experience of a web site by creating a presentation that is more pleasing to the eye, and by making navigation easier. Using VBScript, we can reference the document in one frame from a document in a different frame, or from the document that created the frameset.

Figure 1-19 shows two documents loaded into two frames, named LeftFrame and RightFrame. The VBScript code linked to the button in LeftFrame actually retrieves a value located in a form embedded in RightFrame. The relatively simple code from LeftFrame is shown in Figure 1-20.

Figure 1-19: Using VBScript to retrieve a value in another document

Figure 1-20: The code used in Figure 1-19

As you can see from the code in Figure 1-20, we can also reference the frame itself. This allows us, for example, to have a VBScript in one frame that decides which page the browser needs to load in another frame, based upon some input from the user. We can even reference another VBScript program in another frame.

Create a Document from the Browser "on the Fly"

Using VBScript, we can create a complete new page from the browser without referring back to the server. In fact, this is one of the most valuable assets that VBScript gives us. In theory (although it's somewhat impractical), we could have our entire web site contained in a single document, and then have all of our web pages built on the fly by the browser, based on the users' specifications, needs, and preferences. This is the ultimate in client-side processing.

Although there are several examples of creating dynamic documents with VBScript throughout this book, Chapter 13, Building Dynamic HTML Pages, provides a comprehensive insight into the Document.Write method.

Store, Reference, and Manipulate Data Input by the User

Although VBScript does not currently allow us to store data to the user's disk (with the exception of cookies), we can store data in memory. For example, as the user enters data in a form, VBScript allows us to retrieve this data and store it in arrays or variables that can later be manipulated in some way by our script.

Figure 1-21 shows how we can extract the data input by a user and manipulate it in some way before sending it to the server. The left frame contains a text box and a command button. Sample text is entered into the text box, and when the user clicks the button, the text is manipulated by the VBScript program and-just for this example-a page is generated by the VBScript program and placed in the right-hand frame. The code snippet from this example is shown in Figure 1-22.

Figure 1-21: Using VBScript to manipulate user input

Figure 1-22: VBScript code to manipulate user input

Store, Reference, and Manipulate Data Downloaded from the Server

Let's say we have a fixed data set we wish to include in our page. We can hard code this data set into the HTML page using an array variable. VBScript will then automatically load this data into the memory of the client machine. We can then directly reference this data, again based on input from the user. Another method of implementing this data set is to create our initial page using a server-side script to include data in our page based on the request from the client, in very much the same way as most search engines operate. But with the inclusion of VBScript, we can manipulate this data further once the page has been downloaded to the client browser. In Figure 1-23, for example, data are hardcoded into the HTML page, although it could just as easily be added by a server-side script. The user selects a product from a drop-down list box and enters the quantity required. When the user clicks the Calculate button, the price of the product is accessed from the data array, and a simple calculation is performed to determine the total cost.

Figure 1-23: Using VBScript to manipulate dataa

The complete source code for the example shown in Figure 1-23 appears in Example 1-3. Don't worry about the ins and outs of the code at this stage. It is shown here purely to illustrate how quickly and easily you can perform program- matic tasks at the browser. And as you can see, the majority of code for this example is in fact good old HTML!

Example 1-3: HTML source with VBScript for Figure 1-23

<HTML>
<HEAD>
<TITLE>
Manipulating Data from the Server
</TITLE>
<SCRIPT LANGUAGE="vbscript">
OPTION EXPLICIT
Dim dblPrices(2)
Dim dblShipping
dblPrices(0) = 25.95
dblPrices(1) = 30.50
dblPrices(2) = 50.55
dblShipping = 10.99
Sub cmdCalc_OnClick
Dim intSelected
Dim dblTotal
Dim dblTot

intSelected = frmForm1.cboProducts.SelectedIndex dblTot = dblPrices(intSelected) * frmForm1.txtQty.Value dblTot = dblTot + dblShipping frmForm1.txtTotal.Value = "$" & dblTot End Sub </SCRIPT> </HEAD> <BODY BGCOLOR="white"> <FONT FACE="arial" SIZE=2><B> <CENTER> <H3>Order Form</H3> <P> Select the product you require from the list, then simply enter the quantity, and click the Calculate button to see the total cost. </P> <FORM NAME="frmForm1"> <SELECT NAME="cboProducts"> <OPTION>Product A <OPTION>Product B <OPTION>Product C </SELECT>   Qty <INPUT TYPE="text" NAME="txtQty" SIZE=10> <P> <INPUT TYPE="button" NAME="cmdCalc" VALUE="Calculate"> <P> Total Cost including Shipping and Handling <INPUT TYPE="text" NAME="txtTotal"> </FORM> </BODY> </HTML>

Perform Calculations on Data

Once we have captured data either from the server or as a result of user input, using VBScript to perform calculations on this data is very straightforward, as Figure 1-23 and the HTML source code in Example 1-3 illustrate. Whether a simple calculation or a series of complex calculations is required, VBScript gives us control over form data. VBScript provides a rich assortment of built-in func- tions for numerical operations, and also allows calculations to be performed on dates and times.

Display Messages to the User

One way we can interact with the user is to display a simple message box, or alert box, like the ones we've seen in earlier examples. Messages such as these quickly and easily guide users of our web site or page.

Messages that our program displays do not necessarily have to be fixed; they can be built dynamically, based on the values of program variables. For example, a message box linked to an input form could include the user's name, for that personal touch ("Hey Paul, you didn't enter your Zip Code!"). The techniques for doing this are covered in Chapter 15, Error Handling and Debugging.

Easy Access to Cookies

Cookies (I still don't know why they're called cookies) allow us to store information on the client's machine. The main use of cookies is to store and retrieve data that helps to personalize the web page. For example, we could check to see if a visitor to our site has one of our cookies. If not, we can ask him to complete a simple questionnaire. In the future, when he returns to the site, we can retrieve this information. This allows our web page, for example, to display a banner saying, "Hi Paul, welcome back! We haven't seen you for 6 days." (Yes, we can store the date he last visited us, too.) We could also store the filenames of pages that interest him, and possibly highlight those pages that have changed since his last visit.

There has been much confusion in the past as to how to read or set the value of cookies, or how to "bake a cookie"...seriously!! But VBScript has a very simple and straightforward method of reading and writing cookies, which we will explore in detail in Chapter 5, Controlling the Browser.

Reference and Manipulate a Wide Range of `Add-on' Components-Both ActiveX Controls and Java Applets

The OCX third-party market spawned by Visual Basic will no doubt be mirrored by a plethora of third-party add-ons for use in web pages using VBScript. Using ActiveX components in VBScripted web documents will change the face of the Web, giving us interfaces that look, act, and feel more like the standard windows interface we are all used to. This is not to say that web documents will become "boring" and uniform. On the contrary, the availability of ActiveX components will be a source of further creativity and inspiration. The ingenuity of webmasters and web programmers-who currently have a very limited toolbox-has already shown that the next generation of web pages will be even more fun to look at and use.

We'll discuss ActiveX controls and Java applets in much more depth in a later chapter, and Chapter 9, provides an example that shows how you can add ActiveX controls to your web pages. For now, it's sufficient to realize that the combination of VBScript and ActiveX controls is the backbone of all Microsoft's current and future software architecture plans, and not just those for the Web. In fact, Microsoft Internet Explorer 3.0 itself is mainly the result of cleverly weaving together two ActiveX controls.

Two-Dimensional HTML

In standard HTML, precisely positioning objects on a page can sometimes be quite challenging; positioning objects on top of one another, so that they wholly or partially overlap, is impossible. In contrast, 2D HTML is a new development that allows us to create web pages in which various controls and objects are able to overlap. While new to HTML, this feature has become so standard a part of visual programming environments that it's simply taken for granted. VBScript and ActiveX controls make it possible, since these controls have properties (such as TOP, which determines the distance from the top of the page to the top of the control, and LEFT which determines the distance from the left-hand side of the page to the left-hand side of the control) that can be used to position objects precisely on web pages. Chapter 8, The HTML Layout Control, details how to use and implement 2D HTML.

Server-Side VBScript

So far, in listing the types of tasks that VBScript has been developed to handle, we've focused exclusively on client-side VBScript-that is, on web pages on the client's browser. However, VBScript is also now the preferred language to control pages transmitted by Microsoft Internet Information Server (IIS). Scripts can be written directly within the HTML page to be run at the server, and only their results will be visible to the person calling the page from the browser. You can use server-side VBScript as the glue to interface with components or other services running on the server, such as a SQL Server database. You can also use server-side VBScript to process incoming form data from a web page and to transmit a page on the fly that is sent back to the client. The combination of server-side and client-side VBScript together gives you complete control over your web applications.

Server-side scripting using VBScript is a whole subject on its own, and is really beyond the scope of this book. However, Appendix E, Active Server Pages, intro- duces you to some of the basic concepts of writing scripts for the IIS.

Summary

VBScript can bring our web pages to life. It allows us to incorporate the same objects that we take for granted in the Windows programs we use every day into our web pages, and to control their behavior and appearance by setting their properties. Not only can we access a web page and make changes to it, we can interact with the browser too. We can have control over the browser, the environment, and web documents as never before, and those who can effectively manipulate this control will have a recipe for success. We can empower the users of our web sites to use our web sites in ways that we have only dreamed of until now.

In short, if you're using VBScript, you should let your imagination run wild. What we have seen so far is just a taste of what VBScript can do. The really neat thing about any programming language is that it allows programmers to express their creativity and to realize their imaginations.

The diversity of applications, and the sheer number of web sites and webmasters, will undoubtedly lead to an explosion of imaginative implementations of VBScript web sites and pages. We are entering a very exciting time for the World Wide Web, which is in truth still in its infancy. We're like the kid who's just learned to read. From this point onwards a whole new world of wondrous discoveries is within our grasp.

Back to: Learning VBScript


O'Reilly Home | O'Reilly Bookstores | How to Order | O'Reilly Contacts
International | About O'Reilly | Affiliated Companies

© 2001, O'Reilly & Associates, Inc.
webmaster@oreilly.com