HTML elements provide a rich and compelling way for users to interact with Web sites. Sites that can accept user input and provide visual and aural experiences are fast becoming the most popular stops on the Information SuperHighway. HTML elements combined with VBScript allow users to extend the scope and functionality of Web Pages to include a higher degree of interactivity and control than was previously possible without incurring a lot of client/server transactional overhead. And, when you use VBScript to bring life into your site, you build upon skills you have already developed from previous experience programming with Visual Basic. In this chapter, you learn how VBScript can be used to bring a new dimension to a two-dimensional Web site.
The original purpose of an HTML form was to collect and organize data to be used by the Internet Server. Over time HTML forms have evolved far beyond that original purpose. Although you can still use HTML forms to do standard CGI-based, client/server, and Web-based interactions over the Internet, with the help of a scripting language such as JavaScript or VBScript, you can also use them to analyze and process data on the client side. Thus, you reduce the transactional burdens you place on your server-side programming, making your code more concise and robust.
NOTE: CGI The Common Gateway Interface is a specification that defines a set of standards by which data enters and leaves an Internet server consistently and predictably. Originally developed for the UNIX environment, CGI is used for Internet-based data processing and decision-making routines such as queries and lookups. Programs that do this sort of server-side processing are called CGI scripts. Usually, they are written in a language such as Perl or C.
A Word on HTML Coding Style
HTML keywords are not case sensitive, nor do non-white space value strings require quotation marks. Thus,<INPUT TYPE=RADIO NAME=opFoo VALUE=fooFighter1>is operationally the same as:
<input type=radio Name=opFoo Value=fooFighter1>or
<INPUT TYPE=RADIO name=opFoo value=fooFighter1>Quotation marks are optional for non-white space value assignments but are required if you use value assignments with more than one word. Thus,
<INPUT TYPE=SUBMIT NAME=submit VALUE=Clear>will work. However,
<INPUT TYPE=SUBMIT NAME=submit VALUE=Clear Form>will not work. Rather the correct syntax is:
<INPUT TYPE=SUBMIT NAME=submit VALUE="Clear Form">
There is lot of variety to HTML coding style in the HTML development community. The important thing to consider when you create your pages is that your code should be consistent, well organized, and easy to read.
HTML forms begin with the tag <FORM> and ends with the tag </FORM>. The <FORM> element takes the format:
<FORM ACTION = URL METHOD= post (or get) NAME=aname> . . </FORM>
Where:
ACTION is the server-side Uniform Resource Locator to which the form's data will be passed. Typically, this is a CGI script. However, with the emergence of Microsoft's Active Server Pages initiative, many more URLs are referencing an Active Server Page.
METHOD is the way the data is passed. You can choose from either the POST method or the GET method.
A Word About POST and GET
The GET and POST are the most used methods for sending user information to scripts. The GET method is typically the default method if no method is specified.The GET method sends the user-entered information to the script in the environment variable, QUERY_STRING, which is limited to 255 characters. Usage of the GET method is shown in the following example.
<FORM ACTION="SendData" METHOD="GET">The POST method sends the user-entered information to the script via the server's STDOUT and the script's STDIN. The POST method has no limitations on the amount of character data it can process. Usage of the POST method is shown in the following example.
<FORM ACTION="SendData" METHOD="POST">
NAME is a user-defined ID that identifies the form. This feature is particularly useful when you have Web pages that contain more than one form.
Thus:
<FORM ACTION=http://www.mysite.com/cgi-bin/myscript.exe METHOD=post NAME=myform> . . . </FORM>
denotes a form that will pass its data to a CGI script, myscript.exe on the server www.mysite.com. The form will use the POST method. The name of the form is myform.
Forms are parent elements. This means that the information they gather is generated by other HTML elements that live between the <FORM> and </FORM> tags. An element that lives within a <FORM> is called a child element. This notion of parent and child elements becomes very important when you work with VBScript or JavaScript and the IE Object Model.
You can have more than one form on a page. The NAME attribute of the form delineates one form from another. Figure 35.1 shows the HTML for a Web page with two forms, frmAnimal and frmStooge. Figure 35.2 shows what the HTML looks like when viewed in Internet Explorer.
FIG. 35.1
The <FORM> element is the basic building block for using HTML
elements.
The <INPUT> elements are what you provide the user into which they enter form data and trigger a submission of the form's data to a server on the Internet.
HTML has a standard set of <INPUT> types just as VB has a standard set of controls that you adapt to a particular purpose. And, as with VB control properties, each <INPUT> element has attributes that you configure to accommodate a particular layout need. These <INPUT> element attributes are shown in Table 35.1
FIG. 35.2
HTML elements look and behave very much like the standard Visual Basic controls.
Attribute | Description |
NAME | Defines name of <INPUT>'s data, similar to a variable name. |
VALUE | <INPUT>'s data, similar to the value of a variable. |
TYPE | Defines the type of <INPUT> element--for example, Text, Radio, CheckBox, and so on. |
MAXLENGTH | Specifies the maximum number of characters permitted to be entered in an <INPUT>'s field. |
SIZE | Defines the size (width) of the <INPUT>'s field. Used for Text or Password. |
CHECKED | Sets a check in a CheckBox or sets a Radio to true. |
The <INPUT> element types are described in the following sections.
Text You use the Text type to allow the user to enter textual data. The following code produces the text input box in Figure 35.3:
Name: <INPUT TYPE=Text NAME=txtMain VALUE="Enter your name here" SIZE=40 MAXLENGTH=36>
FIG. 35.3
You can set a default value for <INPUT TYPE=Text> by setting
the VALUE to the data you want to show as default.
Password A Password type is similar to a Text <INPUT> element type, but the characters that the user enters are masked with asterisks (see Figure 35.4). Though the type does offer some measure of security, the type's security can be breached with little difficulty if you do not have a secure transaction. The following example shows how to produce a password box:
Password: <INPUT TYPE=Password NAME=pswMain>
FIG. 35.4
Using a Password <INPUT> type does NOT necessarily mean total
password security.
Submit The Submit button is the <INPUT> type you use to create a button that, when clicked, triggers the submission of a form's data to an Internet server. The browser will show the caption of the Submit type to be the string "Submit," unless the VALUE is assigned another string. The following example assigns the caption Submit Profile, which is shown in Figure 35.5:
<INPUT TYPE=Submit Value="Submit Profile" NAME=Submit>
FIG. 35.5
You can customize the caption of the Submit <INPUT> type by
changing the VALUE= data.
Reset The Reset type creates a button that, when clicked, clears the data from all fields on an HTML form and returns the fields to their default settings (see Figure 35.6).
<INPUT TYPE=Reset Value="Clear Profile" NAME=Reset>
FIG. 35.6
You can custom configure the Reset caption by adjusting the VALUE=
attribute.
Button This feature creates a button that can be referenced with VBScript or JavaScript. You can't really use this <INPUT> type in standard, non-scripted HTML (see Figure 35.7).
<INPUT TYPE=Button Value="Go Back" NAME=cmdBack LANGUAGE=VBScript OnClick=History.Back>
FIG. 35.7
Button <INPUT> types can be used pretty easily with VBScript
or JavaScript.
Radio Radio buttons are used to make exclusive choices. They are used in much the same way that you use an Option control in VB (see Figure 35.8). The tricky thing about Radio <INPUT> types is to understand that, in order to group a set of Radio types to be exclusive of one another, all Radio types to be grouped must have the same value attached to their NAME attribute. When you submit the form, only the VALUE of the chosen Radio type will be sent to the server.
<B>Your gender:</B><BR> <INPUT TYPE=RADIO NAME=opMain VALUE=Male CHECKED>Male<BR> <INPUT TYPE=RADIO NAME=opMain VALUE=Female>Female<BR>
FIG. 35.8
If you want to set a default Radio, include the CHECKED attribute
when you define the <INPUT> tag.
CheckBox CheckBoxes are used to make inclusive choices. The value of the NAME attribute for each CheckBox must be different (see Figure 35.9). When you submit the form, if a CheckBox is checked, its name-value pair will be sent to the server.
<B>Have you had:</B><BR> <INPUT TYPE=CHECKBOX NAME=ckMumps>Mumps<BR> <INPUT TYPE=CHECKBOX AME=ckMeasles>Measles<BR> <INPUT TYPE=CHECKBOX AME=ckChickePox >ChickPox<BR> <INPUT TYPE=CHECKBOX AME=ckNone CHECKED>No Disease<BR>
FIG. 35.9
If you want to default set a check on a CHECKBOX, include the CHECKED
attribute in the tag definition.
NOTE: NAME-VALUE pair When you make an <INPUT> element, you define a TYPE and you assign values to the NAME and VALUE attributes of the element. When the form's data is submitted to the server on the Internet, the AME and VALUE data for the <INPUT> element is sent as a pair associated with the "=" sign. This association is called a NAME-VALUE pair. NAME-VALUE pairs are usually passed to a server side CGI Script or an Active Server Page. The server-side script or ASP (Active Server Page) then parses the VALUE data from the NAME data and acts upon the data as defined in the script or ASP.
For example:You create a TEXT <INPUT> element in which the user is to enter a favorite baseball team. The HTML syntax is:
Favorite Team<INPUT TYPE=TEXT NAME=txtTeam SIZE=40><BR>
The user enters the string "Yankees" in the <INPUT TYPE=TEXT> element. When the form is eventually submitted to the server the NAME-VALUE pair that will be sent is txtTeam=Yankees, where,
txtTeam is the value of the NAME attribute
and
Yankees is the value of the VALUE attribute.
Hidden Hidden <INPUT> types are, well, hidden. They're never shown on the form. They are a good way to send in some data from the form to the server without the user's knowledge. It's as if you have a piece of data embedded in the form that you can send back to the server on a free-ride basis. In the following code example, the author of the HTML attached the name of "VIP Customer" to a HIDDEN input type. When the data is sent back to the server, the value of the HIDDEN input type will also be sent to the server without the user knowing about it.
<INPUT TYPE=Hidden NAME=hidStatus VALUE="VIP Customer">
Image An IMAGE <INPUT> type displays a .GIF image that has the behavior of a SUBMIT <INPUT> type (see Figure 35.10).
FIG. 35.10
You can give some artistic variety to your form with an IMAGE <INPUT>
type.
<B>Magic Button:</B><INPUT TYPE=image NAME=imgMain SRC=gifs/gifbut.gif>
A <SELECT> element is similar to an <INPUT> element in that it allows users to input data to be submitted to an Internet server. However, the <SELECT> element is a little more powerful in that it has the behavior of a Visual Basic listbox or combobox.
The tag begins with <SELECT> and ends with </SELECT>. Within the <SELECT> element you place <OPTION> elements. If you use the attribute, MUTLIPLE, in the tag definition, the element will appear as a list, similar to the Visual Basic listbox. When the element appears as a list, you can submit multiple <OPTION>s to the server. If you omit the MULTIPLE attribute, the element will appear as a drop-down box, similar to a VB combobox, from which you can chose only one <OPTION> (see Listing 35.1 and Figure 35.11).
<FORM METHOD=post ACTION=../cgi-win/ark.exe NAME=frmArk> <FONT SIZE=4 FACE=TIMES COLOR=Red> Select Animals </FONT> <!--Allow multiple selections--> <SELECT MULTIPLE NAME="Animals"> <OPTION VALUE="pig">Pig <OPTION VALUE="goat">Goat <OPTION VALUE="horse">Horse </SELECT> <P> <FONT SIZE=4 FACE=TIMES COLOR=Red> Select a Flower </FONT> <!--Allow only one selection--> <SELECT NAME="Flowers"> <OPTION VALUE="rose">Rose <OPTION VALUE="lily">Lily <OPTION VALUE="daisy">Daisy </SELECT> <P> <INPUT TYPE=Submit Value="Submit" NAME=Submit> </FORM>
FIG. 35.11
<SELECT> elements are similar to a Visual Basic listbox or
combo control.
The <TEXTAREA> element is similar to a TEXT <INPUT> type, the difference being that a <TEXTAREA> element can accept multiple lines of text.
The tag definition begins with <TEXTAREA> and ends with </TEXTAREA>. Any text that appears between the begin and end tags will show up in the field of the <TEXTAREA> (see Listing 35.2 and Figure 35.12).
The <TEXTAREA> element has three attributes, listed in Table 35.2.
Attribute | Description |
NAME | The name of the element (required) |
ROWS | The number of rows in the <TEXTAREA> field |
COLS | The width of the field in characters |
<FORM METHOD=post ACTION=../cgi-win/poll.exe NAME=frmComment> <FONT SIZE=4 FACE=TIMES COLOR=Blue> Do you have a comment?<P> </FONT> <TEXTAREA ROWS=5 COLS=30 NAME=taComment>Enter your comment here. Don't forget to erase this message or it will show up in you comments and that's not something that you would like to happen. </TEXTAREA> <P> <INPUT TYPE=Submit Value="Submit Comment" NAME=Submit> </FORM>
FIG. 35.12
You can use a <TEXTAREA> element as a memo field.
The <SCRIPT> element denotes a section of script code within a Web page's HTML. The tag definition begins with <SCRIPT> and ends with </SCRIPT>. The element has an attribute LANGUAGE that indicates the scripting language used. Listing 35.3 is a snippet of HTML that shows a <SCRIPT> element that is defining an OnClick event handler in VBScript.
<SCRIPT LANGUAGE="VBScript"> <!-- Sub cmdSubmit_OnClick Dim TheForm Dim i Dim MyMsg MyMsg = "All fields must be filled in.If a field is empty, please type: NONE." Set TheForm = Document.frmPurchase For i = 0 to CInt(TheForm.Elements.Length) - 1 If TheForm.Elements(i).Value = "" Then Alert (MyMsg) Exit Sub End If ext End Sub --> </SCRIPT>
As discussed in the preceding section, you use an HTML <FORM> element to group, collect, and submit data to a server on the Internet. The type of circumstances that you would typically apply a <FORM> to are situations in which you want to collect personnel data, input sales order information, or get lookup information for an Internet search.
Figure 35.13 shows an illustration of a Web site that uses the HTML <FORM> elements, <INPUT TYPE=RADIO>, <TEXTAREA>, <INPUT TYPE=IMAGE>, and <INPUT TYPE=HIDDEN> to create a form that allows a user to submit a term or keyword to a server to do a lookup query. Listing 35.4 shows the HTML that's used to create the page.
FIG. 35.13
Lookup and retrieval Web pages use HTML forms.
Notice that instead of using a <TYPE INPUT=SUBMIT> element type to create a Submit button, the creator of this page cleverly uses an <INPUT TYPE=IMAGE> that uses a custom illustration to create a unique Submit button. If the user enters the lookup terms "creating VBScript procedures" in the TEXTAREA, when the user submits the form's data, the following query string will be sent on to the server:
mode=concept&search=creating+VBScript+prodcures&sp=sp
Where
mode=concept is the NAME-VALUE pair for the selected Radio.
& is the character used in HTML to separate NAME-VALUE pairs.
search=creating+VBScript+prodcures is the NAME-VALUE pair that describes that data entered in the <INPUT TYPE=TEXTAREA>.
The "+" character is used in HTML to indicate a space between words.
sp=sp is the NAME-VALUE pair corresponding to the <INPUT TYPE=HIDDEN> element.
NOTE: query string A query string is the string passed to an Internet server when a user clicks a Submit button in an HTML form.
The string is constructed from the NAME=VALUE pairs of the elements in the form which is being submitted.
<HTML> <HEAD> <TITLE>Search - HTML Quick Reference</TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF"> <!-- --> <!-- HEADER --> <TABLE WIDTH=600> <TR><TD WIDTH=600> <IMG SRC="q08671.gif" ALT="book cover" ALIGN=RIGHT> <A HREF="/que/"><IMG SRC="../sevb4/que_sq.gif" ALT="QUE" Border=0></A> <H3>Search the complete text of:</H3> <H2>HTML Quick Reference</H2> </TD> </TR> </TABLE> <!-- --> <!-- INPUT FORM (DO NOT CHANGE)--> <TABLE WIDTH=600> <TR><TD WIDTH=600> <FORM ACTION="/cgi-bin/AT-htmlqrsearch.cgi" METHOD="POST"> Enter<INPUT TYPE="radio" NAME="mode" VALUE="concept" CHECKED> words describing a concept or<INPUT TYPE="radio" NAME="mode" VALUE="simple"> keywords you wish to find information about:<BR> <TEXTAREA NAME="search" COLS=70 ROWS=4></TEXTAREA><BR> <INPUT TYPE="image" NAME="SearchButton" BORDER=0 SRC="/Architext/pictures/AT-search_button.gif"> <INPUT TYPE="hidden" NAME="sp" VALUE="sp"> </FORM> <P> Documentation about <a href="/Architext/AT-queryhelp.html" >making queries</a> is available. <P><P> <B>TIP:</B> If you plan on making multiple queries, you might wish to make a bookmark for this page. <P> </TD> </TR> </TABLE> <HR SIZE=1 NOSHADE ALIGN=LEFT WIDTH=600> <!-- --> <!-- NAVIGATIONAL TOOLBAR --> <TABLE WIDTH=600> <TR><TD ALIGN=CENTER> | <A HREF="/que/developer_expert/htmlqr/">Book Home Page</A> | <A HREF="/que/developer_expert/htmlqr/toc.htm" >Table of Contents</A> | <A HREF="/cgi- bin/placeorder?express=0-7897-0867-1">Buy This Book</A> | <P> | <A HREF="/que/">Que Home Page</A> | <A HREF="/que/bookshelf/">Digital Bookshelf</A> | <A HREF="/que/bookshelf/disclaim.html">Disclaimer</A> | <P> </TD></TR> </TABLE> <!-- --> <!-- FOOTER --> <HR SIZE=8 ALIGN=LEFT WIDTH=600> <TABLE WIDTH=600> <TR><TD ALIGN=CENTER><FONT SIZE=1> To order books from QUE, call us at 800-716-0044 or 317-361-5400. <P> For comments or technical support for our books and software, select <A href = "/general/support/index.html" >Talk to Us</a>. <P> © 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company. <P> </FONT></TD></TR> </TABLE> </BODY> </HTML>
Though HTML forms and <FORM> elements are powerful tools to have in your development toolbox, they are limited. The most fundamental limitation is that the only dynamic interactions you can do with them on the client side are to submit data to an Internet server or clear the form. Conceptually, you have only one event--Click--and two operational client-side methods--submit the data and clear the form's data. That's it! Any other validation or modifications that you may want to make have to be done through a plethora of client/server interactions. This is time-consuming and incurs a heavy burden of server-side transactions and programming to accommodate those transactions.
However, there is a solution to this problem and that is to extend the functionality of standard HTML forms with a scripting language such as VBScript or JavaScript. You'll take a look at this solution in the section "Using VBScript with the HTML <FORM> Elements and Intrinsic Controls," which comes later in this chapter.
When you install Internet Explorer on you computer, you get more than full multimedia access to the Internet and an OLE container in which you can view documents with full OLE functionality (provided the "maker" applications are installed on your system). You also get a full-blown programming environment, VBScript, and the Intrinsic Controls. Just about all the stuff you get with Standard VB you get with Internet Explorer. You can make programs using VBScript that can use CommandButton, OptionButton, CheckBox, and ComboBox controls, and much more. These controls that are built right into the browser are called Intrinsic Controls.
http://www.microsoft.com/vbscript The latest version of VBScript (v. 2.0) allows you to create code that more closely resembles that of Visual Basic. For more information on VBScript, visit the VBScript Web page. This site includes the complete online documentation and numerous other VBScript specific resources.
NOTE: VBScript now has a debugger! The only provision is that you are using IE 3.02 or greater.At the VBSript Web page you can download a debugger that allows you to debug your VBScript code. The debugger embeds itself as part of Internet Explorer, making the executing and debuging process a little simpler than using a separate executable.
The Internet Explorer Intrinsic Controls enable you to create Web pages that look like a typical Visual Basic application. The underlying code for these controls you create through the VBScript scripting engine. A complete listing of the Intrinsic Controls with their VB and HTML <FORM> counterparts can be found in Table 35.3.
Microsoft Forms Control | VB Standard Equivalent | HTML Element Equivalent |
CheckBox | CheckBox | <INPUT TYPE=CHECKBOX> |
ComboBox | ComboBox | <SELECT> |
CommandButton | CommandButtons | <INPUT TYPE=BUTTON> |
Frame | None | <FRAME> |
Image | Image | <INPUT TYPE=IMAGE> |
Label | Label | none |
ListBox | ListBox | <SELECT MULTIPLE> |
OptionButton | OptionButton | <INPUT TYPE=RADIO> |
ScrollBar | ScrollBar | none |
SpinButton | SpinButton | none |
TabStrip | TabStrip | none |
TextBox | TextBox | <INPUT=TEXT> |
ToggleButton | none | none |
You manipulate the Intrinsic Controls at runtime by using VBScript. You insert and define these controls at design time by using the <OBJECT> tag. The tag definition begins with <OBJECT> and ends with </OBJECT>. The attributes for the <OBJECT> tag, as they pertain to the Intrinsic Controls, are shown in Table 35.4.
Attribute | Description |
ID | Specifies the object. For Intrinsic Controls and ActiveX controls, this is similar to the Visual Basic Name property. |
CLASSID | The ActiveX Control Identifier. All ActiveX controls have a unique number by which they can be identified by your system. |
HEIGHT | The height of the control, similar to the Visual Basic Height property. |
WIDTH | The width of the control, similar to the Visual Basic Width property. |
CODEBASE | The server location of the control to be downloaded if the control is not on the client computer. This is not relevant for the Intrinsic Controls because they are built right into Internet Explorer. |
With regard to the Intrinsic Controls, the <OBJECT> tag also has a child tag, <PARAM>. The <PARAM> tag is used to set properties of an Intrinsic Control.
The <PARAM> tag takes the form
<PARAM NAME=PropertyName VALUE=PropertyValue>
For example, if you want to set the caption of an intrinsic CommandButton with the ID cmdEnter to "Enter", the <PARAM> tag would be:
<PARAM NAME="Caption" VALUE="Enter">
This is the Visual Basic syntactical equivalent of
cmdEnter.Caption = "Enter".
Figure 35.14 shows a Web page that uses two Intrinsic Controls: a CommandButton, cmdClickMe, and a TextBox, txtMain. The HTML for the page is shown in Listing 35.5.
FIG. 35.14
Intrinsic Controls can interact with one another without the need to incur
a lot of client/server transactions.
<HTML> <HEAD> <TITLE>Simple VBScript</TITLE> </HEAD> <SCRIPT LANGUAGE="VBScript"> <!-- Sub cmdClickMe_Click() txtMain.Text = "Clicked!" End Sub --> </SCRIPT> <BODY> <OBJECT ID="txtMain" WIDTH=127 HEIGHT=24 CLASSID="CLSID:8BD21D10-EC42-11CE-9E0D-00AA006002F3"> <PARAM NAME="VariousPropertyBits" VALUE="746604571"> <PARAM NAME="Size" VALUE="3329;635"> <PARAM NAME="FontCharSet" VALUE="0"> <PARAM NAME="FontPitchAndFamily" VALUE="2"> <PARAM NAME="FontWeight" VALUE="0"> </OBJECT> <P> <OBJECT ID="cmdClickMe" WIDTH=96 HEIGHT=32 CLASSID="CLSID:D7053240-CE69-11CD-A777-00DD01143C57"> <PARAM NAME="Caption" VALUE="ClickMe"> <PARAM NAME="Size" VALUE="2540;847"> <PARAM NAME="FontCharSet" VALUE="0"> <PARAM NAME="FontPitchAndFamily" VALUE="2"> <PARAM NAME="ParagraphAlign" VALUE="3"> <PARAM NAME="FontWeight" VALUE="0"> </OBJECT> </BODY> </HTML>
Having more controls available to readily add to your Web pages wouldn't have much of a payoff unless you had a way to interact with them. Using a CommandButton without having access to the Click event or a SpinButton without access the SpinDown event would be a waste of time. Fortunately, this limitation does not exist.
Take a look at the code in Listing 35.5. Notice that in addition to some <OBJECT> tags to accommodate the inclusion of the CommandButton and Textbox controls, at the top of the page you have a <SCRIPT> tag that references a Sub, cmdClickMe_OnClick. This is called an event handler. This piece of VBScript is what will be executed when the user clicks the cmdClickMe button.
An event handler is a Sub. In Visual Basic, event handler code blocks are automatically generated by the Visual Basic IDE (Integrated Development Environment). When using VBScript within HTML, you must create the event handlers yourself.
The syntax for an event handler is:
<SCRIPT LANGUAGE="VBScript"> <!-- Sub ControlID_Event `handler code . . . End Sub --> </SCRIPT>
Where,
ControlID is the ID of the control whose event you are handling.
Event is the event to be handled.
Thus, as coded in the event handler cmdClickMe_OnClick, in Listing 35.5, when the user clicks the CommandButton, cmdClickMe, the Text property to the TextBox, txtMain, is set to "Clicked!".
Trying to remember all the events and all the event handler syntax that goes with any given Intrinsic Control can be a chore. To make programming Intrinsic Controls with VBScript easier, Microsoft created a tool to handle most of the drudgery of these sorts of tasks. It's called ActiveX Control Pad. You can get it by downloading it from the Microsoft SiteBuilder site on the Internet. After you get the hang of it, it will save you a lot of time in your programming endeavors.
Figure 35.15 shows the ActiveX Control Pad Script Wizard. Script Wizard is one the many features of ActiveX Control Pad. Script Wizard allows you to write a lot of VBScript with nothing more than a point and a click.
FIG. 35.15
You can use the ActiveX Control Pad's Script Wizard to code a control's event
handler.
www.microsoft.com/sitebuilder/ Download the ActiveX Control Pad from the Microsoft SiteBuilder site.
In addition to using VBScript to write event handlers for Intrinsic Controls, you can also use it to write user-defined subs and functions, just as you would in standard Visual Basic. The benefit of this is that you can write some fairly complex event handlers, the tasks of which are encapsulated in other subs and functions. Using subs and functions helps you avoid writing code that has minimal reuse and is hard to read.
A Word About Commenting
The HTML comment tag begins with <!-- and ends with -->. Anything that appears between these tags is considered to be a comment and not read by the browser.For example:
<!--I am a comment. I am a another comment on another line-->For commenting within a VBScript block, you use the "'" character, just as you would in standard Visual Basic.
For example:
<SCRIPT LANGUAGE=VBScript> <!-- `Send out an error message Alert "Error Message" -->
</SCRIPT>
You write user-defined Subs and Functions in VBScript just as you would in standard Visual Basic, only you place them within the <SCRIPT> tag. You can place more than one Sub or Function within a set of <SCRIPT></SCRIPT> tags.
Figure 35.16 is an illustration of the Web page, FORM3.HTM. The HTML for this page is shown in Listing 35.6. This page is an example of using a user-defined Sub to extend an event handler, in this case the OnSubmit event for the HTML form, frmLookup. (The OnSubmit is the method of the Form object. VBScript considers the <FORM> element to be a Form object.)
FIG. 35.16
Data validation is a typical use for VBScript.
<HTML> <HEAD> <TITLE>Validating a number</TITLE> </HEAD> <SCRIPT LANGUAGE=VBScript> <!-- `'''''''''''''''''''''''''''''''''''' `Checks a value to see if it looks `'''''''''''''''''''''''''''''''''''' like a number Sub CheckNum(NumToCheck) If IsNumeric(CStr(NumToCheck)) Then Alert ("It's a number") Else Alert ("It's not a number") End If End Sub Sub frmLookUp_OnSubmit CheckNum(frmLookup.txtNumber.Value) End Sub --> </SCRIPT> <BODY BGCOLOR=#FFFFFF> <FONT SIZE=5 FACE=TIMES COLOR=#00218C> Validating a number </FONT> <HR> <FORM METHOD=post ACTION=../cgi-win/lookup.exe NAME=frmLookup> <FONT SIZE=4 FACE=TIMES COLOR=Red> Enter a Number: <INPUT TYPE=TEXT NAME=txtNumber> </FONT> <P> <INPUT TYPE=Submit Value="Submit" NAME=Submit> </FORM> <HR> </BODY> </HTML>
You'll notice that the event handler, frmLookUp_OnSubmit calls the user-defined Sub, CheckNum(NumToCheck). CheckNum is pretty straightforward. It takes the value to check as an argument and passes that value on to the intrinsic VB function, IsNumeric(). (You're probably pretty familiar with IsNumeric. It's been around in VB for years!) If the return is true, the Sub displays an Alert Box containing the string, "It's a number". If it's false, the Alert displays, It's not a number. (The Alert method is the VBScript equivalent of the VB MsgBox statement.)
http://www.microsoft.com/vbscript/us/vbslang/vbstoc.htm A complete illustration and discussion of the VBScript Intrinsic Functions are outside of the scope of this chapter. For the most part, all of the VB functions that are not operating system dependent exist in VBScript. In a few cases, the syntax may be modified a bit. For a detailed reference of the VBScript Language go to the Microsoft site.
The significance of the illustration in Listing 35.6 is that it shows you how to use a user-defined Sub to extend a control's event handler. However, as you read this you might be a bit disconcerted. How can you reference an HTML <FORM> element as you would an Internet Explorer Intrinsic Control? Well, while it is true that a <FORM> is not an Intrinsic Control, it is an object in the Internet Explorer Object Model and can be accessed as such. The trick is understanding the Internet Explorer Object Model for Scripting.
Many HTML elements can also be treated as Internet Explorer Scripting Objects. In order to work effectively with VBScript and HTML elements and to see how they can intermingle, you need to understand the Internet Explorer Scripting Object Model.
The Object Model is pretty straightforward, if you understand the "object-ness" of Visual Basic. At the top of the IE Object Model hierarchy is the Window object, which is the parent to all other objects. This arrangement is similar to the Form-Custom Control architecture in Visual Basic (see Figure 35.17). Object referencing works the same in VBScript as in VB:
parent_object.child_object.property = somevalue
Be advised that variable scope and types are a bit tricky. The scope of VBScript variables is described as procedure scope and script scope. What procedure and script scope means is that the variable can be seen only in the Sub or Function if it is declared inside the procedure. If it is declared outside a procedure, it has script-wide scope. A script in this case means an HTML page. All variables in VBScript are of the data type Variant but you must watch the subtype.
The following sections are a brief description of the objects in the IE Object Model. The files used in Listings 35.7 through 35.15 can be found in the /HTML directory on the CD-ROM that comes with this book.
FIG. 35.17
The Internet Explorer Scripting Object Model Hierarchy.
Window The Window is the object at the top of the IE Scripting Object Model. Operationally, it is the Internet Explorer. In Listing 35.7, you see an example of how to use the Alert method to send a message to a user.
Methods: alert, confirm, prompt, open, close, setTimeout, clearTimeout, navigate
Events: onLoad, onUnload
Properties: name, parent, opener, self, top, location, defaultStatus, status, frames, history, navigator, document
<HTML><HEAD> <TITLE>Hello</TITLE> <SCRIPT LANGUAGE=VBScript> <!-- Sub window_onLoad window.Alert "Hello World" End Sub --> </SCRIPT> </HEAD>
Frame The Frame object is similar to and descends from the Window object. Although you can have a collection of frames, each frame has its own property values and its own document.
Methods: See Window object
Events: See Window object
Properties: See Window object
History The History object holds information about what has been in the window before. It gets this information for the browser's History list (see Figure 35.18). In Listing 35.8, you see an example of how to return to a previously viewed Web page.
FIG. 35.18
The Internet Explorer's History list in the Go menu.
Methods: back, forward, go
Events: none
Properties: length
<HTML><HEAD> <TITLE>Back</TITLE> <SCRIPT LANGUAGE=VBScript> <!-- Sub window_onLoad History.back 1 End Sub --> </SCRIPT> </HEAD>
Navigator The Navigator object gives you information about the browser in use. You can find out what browser your client is using by using the appName property of the Navigator object as shown in Listing 35.9.
Methods: none
Events: none
Properties: appCodeName, appName, appVersion, userAgent
<HTML><HEAD> <TITLE>Navigator</TITLE> <SCRIPT LANGUAGE=VBScript> <!-- Sub window_onLoad Alert Navigator.appName End Sub --> </SCRIPT> </HEAD>
Location The Location object encapsulates an URL. You can use the protocol property of the location object to determine the protocol that is currently in use.(see Listing 35.10)
Methods: none
Events: none
Properties: href, protocol, host, hostname, port, pathname, search, hash
<HTML><HEAD> <TITLE>Location</TITLE> <SCRIPT LANGUAGE=VBScript> <!-- Sub window_onLoad Alert Location.protocol End Sub --> </SCRIPT> </HEAD> </HTML>
Script The Script object defines the script used in the Window. Granted, this description is rather vague. At some point, Microsoft will probably extend and enhance the utility of this object.
Document The Document object encapsulates the document in the current window as well as the elements in the document, that is, links, forms, buttons, and ActiveX objects. The objects Link, Anchor, and Form descend from the Document object. An interesting use of the Document object is to write a line of text to the browser, as shown in Listing 35.11
Methods: write, writeLn, open, close, clear
Events: none
Properties: linkColor, aLinkColor, vLinkColor, bgColor, fgColor, anchors, links, forms, location, lastModified, title, cookie, referrer
<HTML><HEAD> <TITLE>Document</TITLE> <SCRIPT LANGUAGE=VBScript> <!-- document.write ("I am writing a line.") --> </SCRIPT> </HEAD> </HTML>
Link The Link object is an encapsulation of an HTML <A HREF...> tag on a given page. It is read-only. Because a link is a member of the links collection (an array of <A HREF...> tags), you need to access an a particular link through the Document object's Links property. To find out how many <A HREF...> tags are on a page, use the Document object Property links. To determine the text of an <HREF>, use the href property of the Link object, as shown in Listing 35.12
Methods: none
Events: onMouseMove, onMouseOver, onClick
Properties: href, protocol, host, hostname, port, pathname, search, hash, target
<HTML><HEAD> <TITLE>Document</TITLE> <SCRIPT LANGUAGE=VBScript> <!-- Sub window_onUnLoad Dim NumOfLinks Dim MyAlertMsg umOfLinks = Cstr(document.links.length) MyAlertMsg = "There are " & NumOfLinks & " links on this page." MyAlertMsg = MyAlertMsg & Chr(10) & Chr(13) MyAlertMsg = MyAlertMsg & "The first link is " & document.links(0).href Alert MyAlertMsg End Sub --> </SCRIPT> </HEAD> <BODY> <P> <A HREF="http://www.whitehouse.gov"> Go to the White House.</A> <P> <A HREF="http://www.senate.gov"> Go to the Senate. </A> </BODY> </HTML>
Anchor The Anchor object is similar to a Link object. The difference is that the Anchor object references all <A> tags in a given document as opposed to <A HREF...> objects.
Methods: none
Events: none
Properties: name Form The Form object represents an HTML <FORM> element in a Document object. You can reference a Form object by either a name or an array index (see Listing 35.13). The Element object is a child of the Form object.
Methods: submit
Events: onSubmit
Properties: action, encoding, method, target, elements
<HTML> <HEAD> <TITLE>The Virtual Music Store</TITLE></HEAD> <FORM method=post action=/cgi-win/mycgi.cgi> Enter your name: <INPUT TYPE=TEXT NAME=yourname> <BR> <INTPUT TYPE=Submit NAME=submit VALUE="Enter Name"> </FORM> </BODY></HTML>
Element The Element object is a control placed in your HTML document by using the <INPUT> tag or the <OBJECT> tag. The <INPUT> tags refer to HTML elements. The <OBJECT> tags refer to Intrinsic Controls and ActiveX Controls. To handle a Click event of an Element object of type Button, code the onClick event of the Element object, as shown in Listing 35.14.
Methods: click, focus, blur, select
Events: onClick, onFocus, onBlur, onChange, onSelect
Properties: form, name, value, defaultValue, checked, defaultChecked, length, options, selectedIndex
<HTML><HEAD> <TITLE>Element</TITLE> <SCRIPT LANGUAGE=VBScript> <!-- Sub btnOK_onClick frmMain.btnOK.Value ="Thank you!" End Sub --> </SCRIPT> </HEAD> <BODY> <FORM NAME=frmMain> <INPUT TYPE=button NAME=btnOK VALUE="Click me"> </FORM> </BODY> </HTML>
Now that you have gotten a pretty extensive overview of HTML elements, the IE Intrinsic Controls, and the IE Object Model, tie it all together. Listing 35.15 shows the HTML for a customer information registration Web page. This code implements many of the features and techniques you read about in this chapter.
<!--04-20-97--> <HTML> <HEAD> <TITLE>The Square Company</TITLE> <SCRIPT LANGUAGE="VBScript"> <!-- Sub submit_OnClick `********************************* `Sub: submit_OnClick ` `Remarks: This sub checks to make sure that: ` 1. All fields are filled in ` 2. The password matches the password confirmation ` 3. The CC expiration date string is a valid date format ` It then submits to the form data to the CGI script, TRANSACT.EXE ` to the "register" CASE. ` `Copyright: 1997 Macmillan Publishing `********************************* Dim TheForm `declare a variable for the form object Dim i `declare a counter variable Dim MyErrMsg `declare a variable to hold the error message Dim PassWord `declare a variable to hold the password Dim ConfirmWord `declare a variable to hold the confirmation Dim s `declare a general string variable `Assign the blank error message to the message variable MyErrMsg = "All field must be filled in. " MyErrMsg = MyErrMsg + "If a field is empty, please type: NONE." `Assign the purchase form to the object variable Set TheForm = Document.frmRegInfo `Transverse all the elements in the form to `make sure that all the fields are filled in. For i = 0 to CInt(TheForm.Elements.Length) - 1 If TheForm.Elements(i).Value = "" Then `If you get a blank, show the error message and `set the cursor to the offender and leave the Sub. Alert (MyErrMsg) TheForm.Elements(i).focus Exit Sub End If ext `Assign the password and the confirmation to the `corresponding variables PassWord = frmRegInfo.txtPassword.value ConfirmWord = frmRegInfo.txtPassConfirm.value `Create the password mismatch error message MyErrMsg = "The password and the confirmation do not match" `Check to make sure the values match If PassWord <> ConfirmWord then `If you have mismatch, show an Error message Alert (MyErrMsg) `Set the focus back to the confirmation textbox frmRegInfo.txtPassConfirm.focus `HiLite the confirmation textbox frmRegInfo.txtPassConfirm.select Exit Sub end if `Check to make sure that the CC expiration date string is a date MyErrMsg = "The Expiration Date entry must be in a valid date format." `Go to the <INPUT TYPE=text NAME= s = frmRegInfo.txtExpDate.value If IsDate(s) = 0 then Alert (MyErrMsg) frmRegInfo.txtExpDate.focus frmRegInfo.txtExpDate.select Exit Sub End if `If you've gotten to here, everything is OK `Submit the data TheForm.Submit End Sub Sub cmdReturn_OnClick `********************************* `Sub: return_OnClick ` `Remarks: This sub returns the user to their previous URL ` ` `Copyright: 1997 Macmillan Publishing `********************************* history.back 1 End Sub --> </SCRIPT> </HEAD> <BODY BGCOLOR=#FFFFFF> <CENTER> <IMG SRC=gifs/logo.gif> <BR><FONT SIZE=6 FACE=TIMES COLOR=#00218C> Customer Registration</FONT> <BR> <TABLE BORDER=1 WIDTH=80%> <FORM NAME=frmRegInfo METHOD=post ACTION=../cgi-win/transact.exe> <INPUT TYPE=hidden NAME=transaction VALUE= hidRegister> <!--Name Data--> <TR> <TD COLSPAN=2><FONT SIZE=2 COLOR=#840084 FACE=arial> First Name:<BR><INPUT TYPE=text SIZE=40 NAME=txtFirstName></TD> </TR> <TR> <TD COLSPAN=2><FONT SIZE=2 COLOR=#840084 FACE=arial> Last Name:<BR><INPUT TYPE=text SIZE=50 NAME=txtLastName></TD> </TR> <!--Address Data--> </TR> <TD COLSPAN=4><FONT SIZE=2 COLOR=#840084 FACE=arial> Address 1:<BR><INPUT TYPE=text SIZE=60 NAME=txtAddress1></TD> </TR> <TR> <TD COLSPAN=4><FONT SIZE=2 COLOR=#840084 FACE=arial> Address 2:<BR><INPUT TYPE=text SIZE=60 NAME=txtAddress2></TD> </TR> <!--City State Zip Country--> <TR> <TD COLSPAN=2><FONT SIZE=2 COLOR=#840084 FACE=arial> City: <BR><INPUT TYPE=text SIZE=50 NAME=txtCity></TD> <TD><FONT SIZE=2 COLOR=#840084 FACE=arial> State: <BR><INPUT TYPE=text NAME=txtState></TD> </TR> <TR> <TD><FONT SIZE=2 COLOR=#840084 FACE=arial> Zip: <BR><INPUT TYPE=text NAME=txtZip></TD> <TD><FONT SIZE=2 COLOR=#840084 FACE=arial> Country: <BR><INPUT TYPE=text NAME=txtCountry></TD> </TR> <!--E-mail, Phone, URL--> <TR> <TD><FONT SIZE=2 COLOR=#840084 FACE=arial> E-Mail <BR><INPUT TYPE=text NAME=txtEmail></TD> <TD><FONT SIZE=2 COLOR=#840084 FACE=arial>Phone: <BR> <INPUT TYPE=text NAME=txtPhone></TD> <TD COLSPAN=2><FONT SIZE=2 COLOR=#840084 FACE=arial> URL: <BR><INPUT TYPE=text SIZE=30 NAME=txtURL></TD> </TR> </FONT> <!--Put in a line across the TABLE--> <TR> <TD COLSPAN=4> <HR> </TD> </TR> <!--Customer ID and Password--> <TR> <TD><FONT SIZE=2 COLOR=#FF0639 FACE=arial> Customer ID: <BR><INPUT TYPE=text NAME=custID></TD> <TD><FONT SIZE=2 COLOR=#FF0639 FACE=arial> Password: <BR><INPUT TYPE=password NAME=txtPassword></TD> <TD><FONT SIZE=2 COLOR=#FF0639 FACE=arial> Password Confirmation: <BR><INPUT TYPE=password NAME=txtPassConfirm></TD> </TR> </FONT> <!--Credit Card--> <TR> <TD COLSPAN=4> <HR> </TR> <TR> <!--Credit Card Type--> <TD><FONT SIZE=2 FACE=ARIAL COLOR=#00218C>Credit Card Type:<BR></TD> <TD COLSPAN=3 ALIGN=CENTER><FONT SIZE=2 FACE=ARIAL COLOR=#00218C> <INPUT TYPE=radio NAME=radCcType VALUE=visa>Visa <INPUT TYPE=radio NAME=radCcType VALUE=mc>MasterCard <INPUT TYPE=radio NAME=radCcType VALUE=amex>American Express <INPUT TYPE=radio NAME=radCcType VALUE=disc>Discover </TD> <!--Credit Card Number--> <TR> <TD COLSPAN=2><FONT SIZE=2 FACE=ARIAL COLOR=#00218C> Credit Card Number:<BR><INPUT TYPE=text SIZE=50 NAME=txtCcNumber></TD> </TR> <!--Credit Card Expiration--> <TR> <TD COLSPAN=2><FONT SIZE=2 FACE=ARIAL COLOR=#00218C> Expiration Date:<BR><INPUT TYPE=text NAME=txtExpDate></TD> </TR> <TR> <TD></TD> <!--Submit Button--> <TD><INPUT TYPE=button NAME=submit VALUE="Submit Customer Info"</TD> <!--Clear Button--> <TD><INPUT TYPE=reset VALUE="Clear Customer Info"</TD> <TD></TD> </TR> </FONT> <TR> <TD COLSPAN=2> <!--Return Button--> <INPUT TYPE=button NAME=cmdReturn VALUE="< Return"></TD> </TR> </FORM> </TABLE></CENTER> </BODY> </HTML>
Notice that the page contains a frmRegInfo and that the form is populated with TEXT, PASSWORD, RADIO, SUBMIT, RESET, and BUTTON <INPUT> types (see Figure 35.19). However, all the data is analyzed and manipulated by using VBScript. These <INPUT> elements are referenced as children objects of the IE Object Model, Form object. Notice too, that the SUBMIT element's default submission behavior (which happens when you press an HTML <INPUT TYPE=SUBMIT> element) is modified by using the OnClick method of the IE Submit object. Thus, you are able to overcome one of the pivotal shortcomings of HTML elements--the ability to analyze and respond to user input before such input is sent on to a server on the Internet.
FIG. 35.19
You can use the <TABLE> element to better organize your forms.
To validate that all <INPUT TYPE=TEXT> element's VALUEs are not empty, the code takes advantage of VBScript's ability to reference elements as members of a collection, thus averting the need to explicitly query the VALUE of every element by name. This is done by querying each item in the Form object's ELEMENTS collection by using a For...Next loop and then using a Window object's Alert method and the Element object's Setfocus and Select methods if errors are encountered.
The History object's Back method is used within the OnClick event of the custom-created Return button. This button was created not as an IE Intrinsic Control, but rather as an HTML element upon which an event handler has been imposed by using VBScript (see Figure 35.20).
FIG. 35.20
You can make a Return button by using HTML elements and VBScript.
Using a scripting language such as VBScript in conjunction with HTML elements is a very flexible, powerful programming technique. You can use this methodology not only with Internet Explorer by using VBScript, but also with Netscape Navigator. All you need to do to have HTML elements be interactive within Netscape Navigator is to use JavaScript instead of VBScript. If you are reticent about taking the time to learn another scripting language, while it is true that JavaScript is syntactically different than VBScript, they are conceptually similar and Internet Explorer supports JavaScript! It might not be the superfluous use of time that you might think it is. In the next chapter, you take a look at how Java and VBScript can be used to create Web pages.
In this chapter, you looked at HTML elements and how you can use them in your Web pages. You also looked at the Internet Explorer Intrinsic Controls and the Internet Explorer Object Model. You've looked at how VBScript can be used to tie all of these different tools and techniques together to form a working Web site, as well.
The following chapters will provide you with additional coverage on creating Web pages:
You might want to check out the following Que books for additional information on VBScript and Web page development:
You might want to check out the following Web sites for additional information on the topics covered in this chapter:
© Copyright, Macmillan Computer Publishing. All rights reserved.