|  | Click Here!

Search the site:
EXPERT SEARCH

| Programming Languages
| Databases
| Security
| Web Services
| Network Services
| Middleware
| Components
| Operating Systems
| User Interfaces
| Groupware & Collaboration
| Content Management
| Productivity Applications
| Hardware
| Fun & Games

EarthWeb sites
Crossnodes
Datamation
Developer.com
DICE
EarthWeb.com
EarthWeb Direct
ERP Hub
Gamelan
GoCertify.com
HTMLGoodies
Intranet Journal
IT Knowledge
IT Library
JavaGoodies
JARS
JavaScripts.com
open source IT
RoadCoders
Y2K Info

- 9 — ActiveX Controls and VBScript

- Why a Scripting Language?
- VBScript

- Embedding ActiveX Objects on a Web Page

- The <OBJECT> Tag

- ClassID
- What's in a Name?
- Data and Types
- The Missing Link

- Specifying Object Parameters
- Control Pad

- Introduction to VBScript

- Adding Script to HTML
- VBScript Features

- If, Then, or Else
- Loop-de-Loop
- Same Old Routine
- What's Your Function?

- VBScript and HTML Forms

- The Main Event
- Assigning Events in HTML
- Form Control Properties

- VBScript and ActiveX Controls

- ActiveX Properties and Methods
- ActiveX and Events

- What's Next

##
9 — ActiveX Controls and VBScript

by John J. Kottler

Welcome to the interactive world of the Internet. In the past, Web pages were composed of static documents and pictures, then sites moved from static, non-changing documents to those generated dynamically by Common Gateway Interface (CGI) scripts on Internet servers. Current Web sites not only offer the ability to find information you're searching for, but also elegant ways to interact with the site. For instance, many sites feature searching capabilities that allow you to enter criteria to use when searching for information. The server takes this criteria, passes it to an appropriate program that performs the search, then returns the results to be displayed within your Web browser. Another good example is the use of Web sites that can be customized, where you can specify what information you're interested in just once; when you revisit that site, only relevant information is displayed, based on your initial choices of interest. A good example of a site that can be customized is MSN, the Microsoft Network, at www.msn.com.

Although much more interesting results can be generated dynamically by CGI scripts and forms, the Web still lacks an interactive edge. CGI scripts provide a mechanism for a Web client to communicate with a Web server; however, the connection is usually quite slow. This certainly doesn't allow for truly interactive applications. To create highly responsive Web pages, the interactive piece must be executed on the client's machine, where it will be most efficient.

Most Web sites today don't offer you true interaction. Rarely do you see something as interactive as a game on a Web site. However, this too is changing. The World Wide Web is rapidly evolving from static information to dynamic information to interactive information. Developments like Sun's Java (www.javasoft.com) and Macromedia's Shockwave (www.macromedia.com) have brought truly interactive applications to the pages of the Web. With these types of applications, it's possible to create multimedia presentations, Windows-type applications, and even games.

As you have already seen throughout this book, Microsoft's ActiveX technology (www.microsoft.com) also allows you to create truly interactive Web pages. By using ActiveX, you can insert rich data objects onto your Web pages to enhance interaction with the user, and Web page developers can create applications similar to those you find for the Windows operating system. For the developer, ActiveX simulates a development environment much like Visual Basic's. In fact, the OCX controls in Visual Basic's tool palette can be used equally as well on an Internet Web page as an ActiveX control can. To enhance the development abilities of Web pages further, Internet Explorer 3.0 even supports VBScript—a language based on Visual Basic's popular language.

NOTE
Although many development tools and languages allow you to use ActiveX controls, not all currently let you create ActiveX controls. The actual controls themselves are commonly developed by using tools such as Microsoft's Visual C++. In the future, you can expect to see other development tools begin to incorporate the ability to create ActiveX controls as well.

####
Why a Scripting Language?

So if ActiveX allows you to create interactive Web pages, why do you need a scripting language in the first place? If you're familiar with development tools such as Visual C++, Delphi, or especially Visual Basic, you can easily see the importance of a development language. When you create an application using any of these development tools, the application consists of two distinct pieces. The first piece is the set of controls available in the application's window. For instance, if you were creating an entry form for a database system, you would place a button to save the information entered on the form, text boxes that allow input for the database, and possibly additional controls, such as radio buttons or checkboxes. Figure 9.1 demonstrates a simple form generated with Visual Basic that could be used in a database application. However, if you merely created the window with these controls and ran the application, nothing would happen. The components are there, but they don't know what they should do.

Figure 9.1. Developing Windows applications consists of two pieces: instructions for the computer and interactive components, such as those on this entry screen.

The second piece of the application is the logic that controls the application—the commands that tell each control what to do. For example, when a user clicks a Save button on a database form, the information on the form should be saved in the database. The actual script associated with clicking the button instructs the computer to perform some validations on the data entered, establish connectivity with a database, and translate and write the information from the form into the database. In a sense, the scripting language is the "glue" that keeps the Web page, and its controls, together.

In actuality, Web pages that you view on your computer are downloaded from a Web server to your computer. These pages are then interpreted by a Web browser on your computer to paint the screen appropriately. Since scripts written in a scripting language help define a Web page's characteristics, they are handled by the Web browser as well. This is often referred to as client-side scripting, since the instructions invoked by the scripts are processed locally on the client's computer.

Another advantage to scripting languages in a Web browser like Internet Explorer is that they allow specific tasks or calculations to be performed locally on the client machine, instead of constantly relying on the server. For instance, when creating an order form for products on a Web site, typically you would be required to submit the quantities of each product you would like to order to the server. The server, in turn, would make sure your entries were acceptable, calculate subtotals, tax, and grand totals, and return the results. With client-side scripting, the validation process and calculations could be performed locally on your computer, allowing error or calculation results to occur immediately instead of being routed first through the Internet. This is particularly useful when you're using Web pages with slow connections.

####
VBScript

VBScript is Microsoft's language that glues components together on a Web page. The language is based on Microsoft's popular development tool: Visual Basic. The language used for creating Visual Basic applications is based on BASIC (Beginners All-purpose Symbolic Instruction Code). This language is simple to use, which is partly the reason for its popularity, yet is powerful enough to produce complex applications. VBScript is a slightly modified version of the Visual Basic language, developed particularly for use in Internet Web pages.

VBScript enables developers to create Web pages with ActiveX controls that allow you to actually do something. The language allows instructions to be performed when certain actions are made by the user or performs other programming tasks, such as mathematical calculations. For instance, in the database example used previously, you could re-create this entry screen for the Web as shown in Figure 9.2.

Figure 9.2. A similar entry form as the one in Figure 9.1, but designed as a form for the Web. In this case, an ActiveX spin-button control was used for the Age field.

In this case, VBScript code is added to the Web page so that when a user clicks on the Save button, appropriate validations are made and errors are reported before posting the data to a database on the Internet Web server. With VBScript, it's possible to check all information entered locally on a client's computer before it's submitted to the server. Therefore, the results can be shown immediately, rather than sent first to the server for processing and then returned. This is a crucial step toward making Web pages interactive. You cannot have a truly interactive application if it requires 30 seconds just to process form data as it's routed through the Internet.

NOTE
Although this chapter discusses using ActiveX and concentrates particularly on VBScript, it's important to realize there are additional languages available for scripting within a Web page. For instance, Netscape Navigator uses the JavaScript language, which is supported by Internet Explorer 3.0; however, Navigator doesn't currently support VBScript. Eventually these browsers, as well as others, will both support scripting languages and allow developers to use them interchangeably within a Web page. This will prove beneficial for developers who want to reuse functions written in one language or another without having to translate the original function to another scripting language.

###
Embedding ActiveX Objects on a Web Page

Now that you have an understanding of what ActiveX controls are and how they can be used with scripting languages provided by the Internet Web browsers, you can examine the process of creating original Web pages by using ActiveX controls. If you're familiar with quick application development tools such as Visual Basic or Delphi, then you'll recall that adding controls to an application you develop is quite simple. With these tools, you simply choose the control from a tool palette and place it in your application's window. Unfortunately, embedding ActiveX controls requires a little more work if you're creating Web pages without the help of an authoring tool, such as Macromedia's Backstage (www.macromedia.com) or Microsoft's ActiveX Control Pad (www.microsoft.com).

ActiveX controls are used with Web pages and controlled by scripting languages found on the client side of the Internet. That is, ActiveX controls are maintained by the Web browser on your computer, not by a server. For these controls to be recognized by your computer system, they must be properly registered in the system registry. A system registry is available in both the NT and Windows 95 operating systems. This registry is actually a database filled with settings the operating system needs to function properly. The type of video hardware your computer uses or what applications are associated with data files are examples of information that may be stored in the registry. Many other applications may also register appropriate information for their functionality. Therefore, the registry contains information on all the ActiveX controls available to the system.

####
The <OBJECT> Tag

To embed an ActiveX control in a Web browser that will be displayed using the Internet Explorer browser, there are several steps required. First, you must use the <OBJECT> HTML tag. This tag indicates to the browser that an ActiveX object will be inserted at the point in the HTML where the tag appears. In addition to the <OBJECT> tag, there is a closing </OBJECT> tag. Between these tags, you can specify additional attributes for the object you're inserting onto a Web page.

The <OBJECT> tag can expect several attributes:

    <OBJECT

        classid=ActiveX Class ID

        id=Object Name on Page

        width=Width of Object in Pixels

        height=Height of Object in Pixels

        data=URL for data for ActiveX object

        type=Internet MIME Type for the data

        standby=Text to display while object and data is loaded

        server=URL to Obtain Control

    >

#####
ClassID

Each ActiveX control is identified in the operating system by its unique identification number. This unique numbering scheme is also used to register OLE objects, such as Word documents or Excel spreadsheets. This unique number, referred to as a GUID (Globally Unique ID), is guaranteed to be different for every registered OLE/ActiveX control. Yet that ID is the same used to identify an ActiveX control on any other machine. For instance, the GUID for Microsoft's Internet Explorer is: {0002DF01-0000-0000-C000-000000000046}. This same number identifies Internet Explorer in either your computer's registry or another user's. Yet this number is entirely different from any other GUID in the registry for any other application.

So how do you find this obscure number? Unfortunately, this isn't a simple task when adding objects manually. Say you wanted to insert a Visual Basic control such as a spin-button control on your Web page. (See Figure 9.2.) The spin-button allows you to change the value of the Age field by clicking the up-arrow or down-arrow buttons. It's possible to use all of Visual Basic 4.0's controls because they are OLE (ActiveX) controls registered in the system registry.

Embedding a control requires the following steps:

1. Run the Registry Editor application
2. Find the control you want to embed on a Web page
3. Copy that control's GUID to the clipboard
4. Use the <OBJECT> tag with the appropriate GUID

You can run the Registry Editor application by launching the regedit.exe application, often found in your Windows 95 or NT directory. This application, shown in Figure 9.3, lists registry entries in the window's left pane and displays appropriate settings for each entry in the right pane.

Figure 9.3. An example of the Windows 95 System Registry.

OLE and ActiveX objects registered in the operating system appear in the My Computer\HKEY_CLASSES_ROOT\ directory of the registry. You can either browse through the registered components or search for a component by name. In either case, once you've found the item you want to embed on a Web page, double-click it to reveal details about the item. If the item is an OLE/ActiveX object, a CLSID (short for class ID) entry is available within the registry for that object. Clicking once on the CLSID entry reveals its default value in the right pane, which is the unique ID (GUID) for the ActiveX/OLE control.

TIP
As you can see, GUIDs are quite long. You could write this number down and re-enter it in your HTML editor, but because of its cryptic nature, you are bound to make a mistake translating the number. Instead, copy the value into the Windows Clipboard. If you double-click the (Default) value found in the right pane, an Edit String dialog box will appear. This second window displays the name of the value you're editing as well as its data. In this case, the GUID is the value data. The data is automatically highlighted, so all you need to do is press Ctrl+Ins to copy the string to the Clipboard. When you're ready to insert the GUID elsewhere, simply paste the results from the Clipboard.
Be careful not to change the GUID by accident. Changing or erasing the GUID will render the ActiveX/OLE control useless.

To complete the process, use the <OBJECT> tag for your Web page, specifying the class ID for the Web object with the GUID you copied to the Clipboard. Listing 9.1 shows the final result of the <OBJECT> tag to embed a Visual Basic spin-button control on a Web page.

Listing 9.1. The <OBJECT> tag can be used to insert ActiveX controls, such as a spin-button.

    <OBJECT

        classid="clsid:B16553C0-06DB-101B-85B2-0000C009BE81"

        id=Spin_Button

        width=31

        height=35

        hspace=20

        vspace=0

    >

    </OBJECT>

#####
What's in a Name?

The second attribute of the <OBJECT> tag is nearly as important as specifying the ID of the object to embed on a Web page. The id attribute is important for identifying an embedded Web page object using scripting languages, such as VBScript. Computers have no problem using the GUID to identify objects on a Web page, but chances are you might; you'd probably prefer using more easily distinguished IDs, such as names. The id attribute allows you to assign a name to the object. For instance, in the example of the spin-button shown in Listing 9.1, Spin_Button was the name given to the control.

It's possible to embed more than one control of the same type at a time on a Web page. Under such circumstances, it becomes even more necessary to name controls. As you'll recall, an ActiveX/OLE control always uses the same GUID to identify itself. Therefore, if you're placing more than one control of the same type on a Web page, both those controls will have the same GUID. To differentiate between multiple controls, each must be assigned a unique name so they can be identified later by program code.

#####
Data and Types

ActiveX controls may expect explicit files for their data as part of the <OBJECT> tag; a control's filename can be specified by using the data attribute of the <OBJECT> tag. This attribute simply holds the URL, which can be used for retrieving a data file from the Internet.

If you are familiar with MIME (Multipurpose Internet Mail Extensions), then you will quickly recognize the value of the type attribute for the <OBJECT> tag. Each data file transferred from the Internet to a Web browser is registered as a particular type of data. Most often it is "text/html" data, which is readily displayed in the browser. However, you can expand these data types and supply ActiveX controls that can display the resulting data within the Web browser. For instance, video/x-msvideo is a valid data type for Microsoft Video for Windows files (.AVI), and audio/x-wav is suitable for digital audio files (.WAV).

These two attributes are used together to transfer data from the Internet and display it appropriately within the Web browser:

    <OBJECT data=skiing.avi

            type="application/avi">

    </OBJECT>

#####
The Missing Link

As ActiveX controls are developed, people accessing a Web page can't be expected to have every type of control registered and installed on their computer system. Fortunately, Microsoft has considered this possibility, so the <OBJECT> tag provides an address specifying where ActiveX controls can be found on the Internet. Therefore, if an <OBJECT> tag specifies using an ActiveX control that isn't in the system registry, the server attribute tells the browser where it can retrieve that ActiveX control.

####
Specifying Object Parameters

You probably noticed that the <OBJECT> tag requires a closing </OBJECT>. Yet until now, there has been no additional HTML information between these tags. Any typical HTML information between these two tags is ignored by browsers that support the <OBJECT> tag. However, there is one type of HTML tag that's accepted between these two: the <PARAM> tag.

Most ActiveX controls you place on a Web page have attributes you can modify, often referred to as the control's properties. These properties may be set by VBScript, as you will see shortly, or by using the <PARAM> tag. An example of a property that can be set for the spin-button control covered in this chapter is its background color. For this example, make the background color white.

The <PARAM> tag accepts two parameters:

    <PARAM NAME=Name of property to change

          VALUE=Value to set property to

    >

Therefore, to set the background color of the spin-button control to white, you would use the <PARAM> tag in Listing 9.2 to set the backcolor of the spin-button:

Listing 9.2. The <PARAM> tag allows you to set properties of an object.

    <OBJECT

        classid="clsid:B16553C0-06DB-101B-85B2-0000C009BE81"

        id=SpinButton

        width=15

        height=19

        hspace=0

        vspace=0

    >

    <PARAM NAME="backcolor"

           VALUE="16777215"

    >

    If you had ActiveX, you'd see a spin-button control.

    </OBJECT>

NOTE
Determining the decimal value for colors can be an arduous process; this is the formula:
color_value = red + (256 * green) + (65536 * blue), where the values for red, green, and blue range between 0 and 255.
You can also find these values using the RGB function in Visual Basic or, more simply, by using the Web Helper application included on the CD-ROM with this book.

TIP
To determine the properties, methods, or events for an ActiveX object, you must have adequate documentation for that object. If you use Visual Basic 4.0, you can test ActiveX controls and experiment with their properties, events, and methods in that environment. For instance, you can easily examine the properties available in an ActiveX control by viewing the Properties window for that control in Visual Basic.

Typical HTML text and graphics may be ignored between the <OBJECT> tags under ActiveX-aware Web browsers, but that same information will be displayed by browsers that don't support the <OBJECT> extension. Therefore, you can substitute standard text or graphics between the <OBJECT> tags that inform the user of a non-ActiveX Web browser that an ActiveX control exists on the page. Listing 9.2 contains text that's displayed only on browsers that aren't ActiveX enabled.

####
Control Pad

As you can see, the process of manually embedding ActiveX controls on a Web page is quite tedious. To make this easier for Web developers, many third-party companies are creating authoring tools that support embedding ActiveX controls. Microsoft also offers a utility called ActiveX Control Pad. With Control Pad,you can insert an ActiveX control into your HTML by selecting the control from a list, sizing the control graphically, then setting the properties in a dedicated window. The <OBJECT> tag and all related settings are then automatically generated and inserted into your HTML. This software is available for download at Microsoft's Web site (www.microsoft.com).

When you first start the ActiveX Control Pad, you are greeted with a skeletal HTML file in an editor interface. The essential tags for every HTML page are automatically generated in the editor's file. To insert an ActiveX control, simply choose Insert ActiveX Control[el] from the Edit menu. A list of all valid ActiveX controls registered on your system are then displayed. You can simply double-click on any control to embed that control within your Web page. For example, you might embed the Microsoft Forms 2.0 TextBox, which creates a standard input text field in a Web page.

Once you have selected the ActiveX control to embed, the ActiveX Control Pad displays two windows: one that allows you to graphically specify the size of the control you're embedding and a second that lists all the properties that may be set for that control. Figure 9.4 shows these windows as they appear for the Microsoft Forms 2.0 TextBox control.

Figure 9.4. The ActiveX Control Pad program allows you to easily specify the properties of ActiveX controls embedded on a Web page.

To see the results in HTML format, simply close these properties windows, and the HTML will be generated automatically and placed into the source code displayed in the ActiveX Control Pad.

TIP
Make sure you have positioned your text cursor at the location in your HTML source where you want to embed an ActiveX control before acutally inserting the control. The HTML <OBJECT> tag for the control is inserted in the source code at whatever position your text cursor was at last. You should make sure this cursor is waiting on a new line so that the <OBJECT> tag will not disrupt the rest of the HTML source.

Later, if you decide to change properties for an ActiveX control once it has been placed in your HTML code, you can simply click the button with a blue cube that appears next to the <OBJECT> tag for that control. The property window is then displayed for you to make changes.

The ActiveX Control Pad offers an easy solution for embedding ActiveX controls on a Web page. It also features a wizard for writing VBScript as well as a tool for creating HTML layouts. Chances are you'll use the ActiveX Control Pad to embed controls on your Web pages in the future because of its ease of use. However, it's also important to understand each of the tags used for embedding controls in an HTML document.

###
Introduction to VBScript

Now that you have a familiarity with ActiveX controls and embedding them within your Web pages, it's time to learn how to work with these controls through programming. This requires a scripting language—in this case, VBScript.

VBScript is a language for the Web browser based on the Visual Basic development language. Some of the fundamentals of VBScript development are covered in this chapter; however, a complete review of the language in detail is far beyond the scope of this book. Instead, if you're interested in detailed information about VBScript, visit Microsoft's VBScript site (www.microsoft.com/vbscript). You can also get additional information about the Visual Basic development language from several books, such as Teach Yourself VBScript in 21 Days, published by Sams.net Publishing, and Teach Yourself Visual Basic 4 in 21 Days, Third Edition, published by Sams Publishing.

####
Adding Script to HTML

Since VBScript functions on the client computer, the script commands must be transferred to the client computer. Therefore, VBScript, like other scripting languages for Web browsers, can be found embedded in the HTML documents that make a Web page.

To insert VBScript functionality in an HTML document, use the <SCRIPT> and </SCRIPT> tags. Like the <OBJECT> tags, anything between the <SCRIPT> tags is considered commands for a scripting language. This is the basic use of the <SCRIPT> tags:

    <SCRIPT LANGUAGE="VBS">

        ...

        VBScript language commands

        ...

    </SCRIPT>

You might have noticed that the <SCRIPT> tag accepts a language attribute. To allow multiple scripting languages within a single browser, you can specify what scripting language is found between the <SCRIPT> tags. This will allow developers to create programs using either JavaScript, VBScript, or both interchangeably within the same Web page.

NOTE
Scripting language instructions should appear near the beginning of HTML files. ActiveX controls can trigger VBScript that exists anywhere within a Web page. HTML form controls that trigger VBScript must find the VBScript before the actual HTML form in the file.

####
VBScript Features

VBScript is a programming language, so it can accomplish almost any task. You can easily create complex formulas with conditional logic. You can also link controls on a form to perform particular actions when invoked. VBScript code consists of calculations performed in a logical order.

The power of a programming language lies in its ability to execute different tasks or functions depending on particular criteria. VBScript supports conditional logic, the ability to test criteria and perform actions based on whether a condition is true or false. VBScript also supports the concept of loops. Certain programming functions may require several iterations to build a result, so you can specify sections of VBScript code that should be executed several times (looped). These loops may be stopped after a set number of iterations, or conditionally when test criteria are met.

#####
If, Then, or Else

The If statement in VBScript is one method of testing whether criteria have been met in the application. When programming VBScript, it's important to realize that you must explicitly indicate which sections of the code are to be executed. For example, when using conditional logic, you must make clear which sections of VBScript code are executed when a condition is true or false.

Typical If...Then statements take on the following structure:

    If condition then

        ... VBScript to execute when result is true

    Else

        ... VBScript to execute when result is false

    EndIf

Conditional tests could be as simple as if color="red", or if age>21, or they may be complex algorithms. In the structure of this If...Then statement, all VBScript that falls between the If line and the else line executes when the result of the condition is true. Likewise, all code between the Else and Endif lines executes when the result is false.

#####
Loop-de-Loop

Programming tasks that execute more than once in a row can be done through looping statements. Like If statements, looping statements require definitive starting and ending points that indicate what sections of the VBScript code are executed more than once.

Loops are typically accomplished using either the For...Next statements:

    For index = starting value to ending value

        ... VBScript to execute multiple times

    Next

or with While...Wend statements:

    While true condition

        ... VBScript to execute multiple times

    Wend

In the For...Next scenario, you specify definite starting and ending values. The index of the For loop increments, starting from the starting value for the loop, and stops incrementing when it reaches the ending value. Each time the index advances, the VBScript code within the For and Next statements is executed.

While...Wend loops iterate continuously until a particular condition is met. In a sense, the While portion of the loop acts similarly to an If condition. Once the condition evaluates as being true, the looping process is stopped.

NOTE
Be careful to avoid "infinite" loops, which are loops that never terminate. Infinite loops may cause your operating system to slow to a crawl or cause the Web browser to halt entirely. Make certain that any loops you create have realistic endpoints that can be met.

#####
Same Old Routine

So far, you have seen how VBScript specifies blocks of code used within conditional logic statements as well as looping statements. Another method for grouping VBScript code together is using sub-routines. Typically, sub-routines have fragments of code that are reused routinely throughout an application. For instance, if you consistently use 10 lines of VBScript to format a text string, you could bundle those lines of code together in a sub-routine. Then, at each instance in your application that requires this sub-routine, you simply type one line of code that executes the sub-routine, not the entire 10 lines.

This makes programming not only easier and faster, but also more accurate. By using sub-routines for common tasks, an application is easier to maintain because changes need to be updated in only one sub-routine instead of in the countless places duplicate code would appear otherwise.

Sub-routines are even more productive because they accept parameters of their own. It's quite possible to pass a value to be processed to a sub-routine, which makes sub-routines more generic for use with different data in an application. For example, in a sub-routine that accepts two numbers, adds them together, and displays a message box with the result, the two numbers passed as parameters to the sub-routine could be any two numbers.

VBScript defines functions by using the following syntax:

    Sub name of sub-routine(parameter1, parameter2, ...)

        ... VBScript within sub-routine

    End Sub

Like ActiveX controls, the name of the sub-routine allows you to identify which one you would like to use elsewhere in your application.

#####
What's Your Function?

Functions are very similar to sub-routines; they group a series of VBScript commands together for easy reusability and also accept input parameters, as needed. The difference is that functions not only accept parameters, they also return a result.

The following defines a function:

    Function name of function(parameter1, parameter2, ...)

        ... VBScript within sub-routine

        name_of_function=result of VBScript

    End Function

Since functions return values, they usually return the results after appropriate processing within the function has finished to create that result. To return values from functions, you must set the name of the function to the end result value. For instance, Listing 9.3 demonstrates a function that subtracts a given number of years (passed as a parameter to the function) from the current year.

Listing 9.3. Functions written with VBScript can return results for other sections of an application.

    function CalculateBirthYear(UsersAge)

        ThisYear=right(date,2)

        CalculateBirthYear=ThisYear-UsersAge

    end function

###
VBScript and HTML Forms

Although ActiveX is a powerful mechanism for creating interactive Web pages, there was a time when an interactive Web page consisted merely of HTML forms. HTML forms, however, aren't in danger of extinction. Rather, client-side scripting languages, such as VBScript, will complement HTML forms to make them more useful.

This section introduces you briefly to key concepts involved in connecting HTML form objects with client-side scripting languages. Complete coverage of this topic would clearly extend beyond this book's original intent, so for additional reading on client-side scripting languages, consider reading Teach Yourself JavaScript in a Week, published by Sams.net Publishing.

####
The Main Event

VBScript, like other scripting languages such as JavaScript, allows you to attach program code to your objects on an HTML form. The code you write using VBScript is executed, depending on an event that a control on an HTML form triggers. Table 9.1 lists a sampling of common events found in scripting languages such as JavaScript and VBScript.

Table 9.1. Several events may be processed for an object in a scripting language like VBScript.

    Events
    Description
    Applies To
onFocus | Code to be executed when an object is activated. | Text Fields
| Typically, activation is either through clicking on or tabbing to an object. | Text Areas Selections
onBlur | The opposite of onFocus, onBlur code will be executed when you click on an object other than the current object or tab off the current object. | Text Fields Text Areas Selections
onSelect | When you highlight text in a entry field, the onSelect code will be executed for that object. | Text Fields Text Areas
onChange | Code for onChange events is executed when the value of a field has been changed. | Text Fields Text Areas
onClick | When you click on an object, the scripting code for that object's onClick event is executed. | Buttons Radio Buttons Check Boxes Submit Buttons Reset Buttons
onSubmit | If you wish to execute scripting code when the Submit button has been clicked, you can use the onSubmit event. | Form Submission

Events are simply actions that can be triggered by an object on a form. For instance, button objects contain a "click" event, meaning that when a user clicks the mouse on a button object on a form, the action notifies VBScript. VBScript, in turn, can take that information and attach code to the event. In this way, program code can be executed when a button is clicked on a form.

####
Assigning Events in HTML

To properly use events in VBScript, you must assign the events to be used with each object on the HTML form, which also indicates what VBScript sub-routine to execute when the event is triggered. Events can be associated to the input object created on a form by using HTML's <INPUT> tag.

As you will recall, the <INPUT> tag instructs Web browsers to create input controls for a form in HTML. It also specifies specific properties for the type of control being created. For instance, you can specify the width of an entry field to limit the length of input. Similarly, you can assign events to input objects and describe the actions to perform when the event is triggered.

The <INPUT> tag allows you to place text entry boxes, as well as checkboxes or radio buttons, on an HTML form. Each of these objects, when given a name on your HTML form, can then be referenced with VBScript. To specify what type of control to use on a form, the TYPE property of the <INPUT> tag can be set to text, checkbox, or radio. You can learn more about the <INPUT> tag by consulting other books, such as Teach Yourself Web Publishing with HTML in 14 Days, Professional Reference Edition, and HTML and CGI Unleashed, both published by Sams.net Publishing.

Listing 9.4 demonstrates the use of the onBlur event for an entry field.

Listing 9.4. Events can be triggered for input objects on HTML forms.

    <INPUT  NAME=FName

            TYPE="text"

            SIZE=20

            onBlur="CheckFName()"

    >

In this case, when a user presses the Tab key to move out of the First Name field when entering information, the onBlur event is triggered and the CheckFName subroutine is executed before the input cursor leaves the field.

TIP
Although you can write program code within the event assignments for the <INPUT> tag, you should call sub-routines or functions to accomplish the task instead. Otherwise, maintaining the script's code and the object's attributes within the tags may become confusing.

####
Form Control Properties

Often, you want to be able to retrieve information from particular objects on an HTML form. For example, when a user clicks a Save button, that button's onClick event triggers a subroutine to be executed. The script in that subroutine could then read values from the entry fields the user keyed in and verify that they aren't empty and they follow correct formatting. To do this, the script in the sub-routine must be able to retrieve information (and possibly update) in the entry fields.

Previously, in Listing 9.4, you learned how to attach events to input objects on HTML forms. In this example, the CheckFName sub-routine is called when focus is removed from the First Name entry field. For CheckFName to verify that the First Name field is not empty, it must be able to retrieve the value for that field.

Listing 9.5 demonstrates how to retrieve information from a field and check whether it's blank. In this example, if the field is blank, a warning message is displayed. The form in this example was created by using a <FORM> tag named MyForm.

Listing 9.5. Simple field input verification can be done by using client-side scripting.

    sub CheckFName()

        if document.MyForm.FName.value="" then

            Alert("You need to enter your first name.")

        endif

    end sub

To access the value of a field, you must use its value property. However, to properly access this property, you must explicitly qualify the control, so you must include any relationships the control has with the Web page. In this case, the field FName is part of the MyForm form, which is part of the Web page document. MyForm and FName are components created by the HTML source code, but document is a reserved word in VBScript, indicating the current Web page document. It's important to specify that you are working with controls on a document, since you can also indicate controls in other objects, such as the browser's history list or ActiveX controls.

###
VBScript and ActiveX Controls

Just as you can assign and receive information about properties for form controls, you can perform the same task with ActiveX controls. In a sense, you could think of ActiveX controls as extensions to HTML input objects. ActiveX controls contain events, properties, and methods that you can invoke and use within a scripting environment, such as VBScript.

####
ActiveX Properties and Methods

Accessing ActiveX controls with VBScript is simple. When you originally embedded an ActiveX control on a page by using the <OBJECT> tag, you assigned that object a unique name to use within VBScript. Therefore, to reference an ActiveX control, you simply use that name in your VBScript code. You can use that name to reference any of that control's properties or methods.

NOTE
Properties, methods, and events for ActiveX controls vary widely between controls. To effectively use an ActiveX control, you must have adequate documentation on its properties, methods, and events. You can also use other development tools, such as Visual Basic 4.0, to explore the capabilities of ActiveX controls.

Listing 9.6 demonstrates setting the foreground color of an ActiveX label control to a random color.

Listing 9.6. Properties of ActiveX controls can be easily set.

    sub SetLabelColor

        MyLabel.forecolor = rnd() * 16777216

    end sub

In addition to supporting properties that can be set and retrieved, ActiveX controls also support functions of their own that you can invoke. For instance, in the next chapter, "Using the ActiveMovie Control," you will learn more about ActiveMovie, an ActiveX control that enables you to control video playback on your computer. This control features several functions that control a video file; they are referred to as methods in ActiveX controls.

To invoke a method in an ActiveX control, use the same technique you would to access a property, but instead of using a property name, use an appropriate method. Notice however, that most methods, like functions in VBScript, accept parameters of their own; these input parameters are passed within parentheses after the name of the method. Additionally, since most methods are functions, be aware that they may return a value you can use elsewhere in your VBScript code.

Listing 9.7 demonstrates the use of an ActiveX control's method. The function StartMovie invokes the run method of the ActiveMovie ActiveX control. Since the run method is a function, it returns a value that's stored in VBScript as result.

Listing 9.7. Methods of ActiveX controls can be invoked by VBScript.

    SUB StartMovie

        result = ActiveMovie.Run

    END SUB

####
ActiveX and Events

So far, you've seen how VBScript code can affect ActiveX controls. However, ActiveX controls can just as easily affect VBScript. For instance, when using the spin-button mentioned earlier in this chapter, you can click the up and down arrows of the spin button. However, those actions are worthless if the VBScript cannot receive notification that you clicked the up or down arrows. The VBScript must be able to handle the event of a user clicking on the up or down arrows for the spin-button control and act appropriately.

Events that can be triggered for ActiveX controls vary, depending on the ActiveX control. Once you have found the event you want to capture from an ActiveX control, you must create a sub-routine in your VBScript application that executes when the event is triggered. The name of the sub-routine must be the ID that you assigned to the ActiveX control used in your VBScript code, followed by an underscore character, then the name of the event. For example, if a SpinButton control was placed on a Web page and given the ID "SpinButton," the following would illustrate the SpinUp event used in VBScript for this control:

    sub SpinButton_SpinUp()

    ...

    end sub

Once the event's sub-routine has been created in VBScript, you may include any code to be executed for that event within its sub-routine.

Listing 9.8. demonstrates two events for a spin-button control. In this example, SpinButton is the name of the ActiveX control used on the Web page as it was defined with the <OBJECT> tag. SpinDown and SpinUp are two events triggered by the SpinButton ActiveX control.

Listing 9.8. Events from ActiveX controls can be trapped and processed in VBScript.

    sub SpinButton_SpinDown()

        age=document.MyForm.AgeField.value-1

        if age<1 then age=1

    0    document.MyForm.AgeField.value=age

    end sub

    sub SpinButton_SpinUp()

        age=document.MyForm.AgeField.value+1

        if age>100 then age=100

        document.MyForm.AgeField.value=age

    end sub

###
What's Next

In this chapter, you have been introduced to ActiveX technology and how to use it within Web pages. You have also learned the fundamentals of VBScript and the benefits a client-side scripting language offers, particularly when interacting with ActiveX controls. In the next chapter, "Using the ActiveMovie control," you will get the opportunity to investigate the possibilities of a robust ActiveX control: ActiveMovie, which allows you to control video content within a Web page. In the following chapter, you will also see the source code of a Web page designed with ActiveX controls.

| Use of this site is subject certain Terms & Conditions. Copyright (c) 1996-1999 EarthWeb, Inc.. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Please read our privacy policy for details.