All Categories :
ActiveX
Chapter 5
Interfacing VBScript with an HTML
Form
CONTENTS
A lot of the VBScript work you undertake is linked in some way
to the form because VBScript is ideal for interfacing with user
inputs. As you saw in Chapter 2 "Using VBScript with HTML
Controls," you can easily and quickly add VBScript to current
HTML pages without major renovation. In this chapter, you'll learn
about three HTML form elements that probably cause the most confusion
when it comes to adding script to a form. Text boxes are straightforward,
but the three elements that afford choice to the user are not.
The three choice elements in HTML forms are as follows:
- SELECT isn't strictly a control because it isn't
specified with the <INPUT> tag; however, it is
used very frequently and is probably the easiest of the three
to work with. Select lists are specified as follows:
<SELECT NAME="MySelect">
<OPTION>The First Option
<OPTION>The Second Option
</SELECT>
- RADIO is the small, round indented button that designates
one of many choices when it's used together with other radio buttons
of the same name. A radio button is specified within an INPUT
tag as follows:
<INPUT TYPE="radio" NAME="myRadio" VALUE="OptionValue">
- CHECKBOX is the small, square indented box that is
either on (checked) or off (unchecked). This gives the user a
series of options to select-one, none, some, or all. A checkbox
is specified within an INPUT tag as follows:
<INPUT TYPE="checkbox" NAME="myCheck" VALUE="CheckValue">
In this chapter, you create a form from which the user can select
a range of options. Specifically, this is part of the order form
for the fictitious "Mega Choice Mail Order" Web site,
promoting its new product, the "LazeeGeek Computer Users
Head Prop," as shown in Figure 5.1. I think I ate too much
cheese last night!
Figure 5.1 : The multichoice order form.
As you see, the users select from a range of optional extras using
the checkboxes; they select one size using the radio buttons.
Finally, they select the color of their choice from a drop-down
list, courtesy of a <SELECT> tag.
Listing 5.1 shows the complete source code for the Web page (mega1.htm),
and you can find it on the CD-ROM that accompanies this book.
Each task in this chapter breaks down a specific section of the
source code to show you how the code fits together. Note that
I created this whole page with Notepad; however, you can use the
ActiveX Control Pad's Text Editor or your own favorite HTML editor
if you want. The line numbers shown in the following source code
are for the purpose of explanation and should not form part of
the final document.
Listing 5.1. mega1.htm.
<HTML>
<HEAD>
<!-- ***************************************
* LAZEEGEEK HEAD PROP EXAMPLE *
***************************************
-->
<TITLE>
Mega Choice Mail Order
</TITLE>
1:<SCRIPT LANGUAGE="vbscript">
2:<!--
3:OPTION EXPLICIT
4:Sub Button1_OnClick
5:'====================DECLARE VARIABLES AND CONSTANTS===============
6: Dim intColor
7: Dim i
8: Dim strOptExtras, strTheSize, strTheColor, strMainMessage
9: Dim intOptQty, intResponse
10: Dim blnSize
11: Dim CRLF
12: CRLF = Chr(10) & Chr(13)
13:'=====================DETERMINE SIZE SELECTION======================
14:blnSize = False
15:For i = 0 to Document.OrderForm.Elements.Count -1
16: If Document.OrderForm.Elements(i).Name = "choice1" Then
17: If Document.OrderForm.Elements(i).Checked Then
18: blnSize = True
19: strTheSize = "Size: " & Document.OrderForm.Elements(i).Value
20: Exit For
21: End if
22: End if
23:Next
24:If Not blnSize Then
25: Alert "You must select a size"
26: Exit Sub
27:End If
28:'======================DETERMINE COLOR SELECTION======================
29:intColor = Document.OrderForm.Colors.SelectedIndex
30:strTheColor = "Color: " & Document.OrderForm.Colors.Options(intColor).Text
31:'======================DETERMINE OPTIONAL EXTRAS======================
32:strOptExtras = "Options: "
33:intOptQty = 0
34:If Document.OrderForm.option1.Checked Then
35: strOptExtras = strOptExtras & Document.OrderForm.option1.Value & " "
36: intOptQty = intOptQty + 1
37:End If
38:If Document.OrderForm.option2.Checked Then
39:If intOptQty > 0 Then
40: strOptExtras = strOptExtras & "and "
41:End if
42: strOptExtras = strOptExtras & Document.OrderForm.option2.Value & " "
43: intOptQty = intOptQty + 1
44:End If
45:If Document.OrderForm.option3.Checked Then
46:If intOptQty > 0 Then
47: strOptExtras = strOptExtras & "and "
48:End If
49: strOptExtras = strOptExtras & Document.OrderForm.option3.Value
50: intOptQty = intOptQty + 1
51:End If
52:If intOptQty = 0 Then
53: strOptExtras = "No Options Required"
54:End If
55:'========================SHOW MESSAGE ==================================
56:strMainMessage = "Thanks for your order" & CRLF
57:strMainMessage = strMainMessage & strTheSize & CRLF
58:strMainMessage = strMainMessage & strTheColor & CRLF
59:strMainMessage = strMainMessage & strOptExtras & CRLF
60:strMainMessage = strMainMessage & "Is this correct?"
61:intResponse = MsgBox(strMainMessage,36,"Order Details")
62:End Sub
63:-->
64:</SCRIPT>
</HEAD>
<BODY BGCOLOR="white">
<FONT FACE="arial" SIZE=2>
<CENTER>
<TABLE>
<TD>
<H2>Mega Choice Mail Order</H2>
<H3>The New <I>LazeeGeek</I> ® <BR>Computer Users Head Prop</H3>
<TD>
<IMG SRC="headprop.gif">
<TR>
</TABLE>
<FORM NAME="OrderForm">
<TABLE CELLPADDING=20 CELLSPACING=20>
<!--COLUMN ONE ---- OPTIONAL EXTRAS -->
<TD VALIGN=TOP>
<B>Optional Extras</B><BR>
Padded Headrest<INPUT TYPE="checkbox" NAME="option1" Value="Padded Headrest"><BR>
Cup Holder<INPUT TYPE="checkbox" NAME="option2" Value="Cup Holder"><BR>
Shock Absorber<INPUT TYPE="checkbox" NAME="option3" Value="Shock Absorber"><BR>
<!--COLUMN TWO ---- SIZE CHOICE -->
<TD VALIGN=TOP>
<B>Sizes</B><BR>
12 Inches<INPUT TYPE="radio" NAME="choice1" Value="12 Inches"><BR>
18 Inches<INPUT TYPE="radio" NAME="choice1" Value="18 Inches"><BR>
24 Inches<INPUT TYPE="radio" NAME="choice1" Value="24 Inches"><BR>
<!--COLUMN THREE ---- COLOR & BUTTON -->
<TD VALIGN=TOP>
<B>Colors</B><BR>
<SELECT NAME="Colors">
<OPTION>Brushed Aluminium
<OPTION>Black
<OPTION>Blue
<OPTION>Green
<OPTION>Red
</SELECT><P>
<INPUT TYPE="button" NAME="Button1" VALUE="Place your order now">
<TR>
</TABLE>
</FORM>
</BODY>
</HTML>
To give you some understanding of how VBScript interacts with
forms and form elements, I'll briefly discuss the hierarchy of
HTML objects. A document is an object that belongs to the window
object (that is, the window object is its parent). Because the
window object is implicit, you usually do not need to specify
it in the code line. You can have only one document per window;
however, a frame is treated as a window.
Note |
If the document is held within a frame, you must explicitly call the frame first. To learn about frames with VBScript, see Chapter 18, "Interacting with the Browser."
|
A form object belongs to the document, and a document can have
any number of forms. The element objects-such as text boxes and
other input controls-are objects that belong to the form, and
again, a form can have any number of elements. To access the value
of a form element from your script, you use the following syntax:
Document.FormName.ElementName.Value
When either building or amending an HTML form that you intend
to interface using VBScript, the main thing to keep in mind is
that you must give your form and its elements a name. Giving them
names simplifies matters greatly, although it is not absolutely
necessary as I now demonstrate with the following short example:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="vbscript">
Sub CommandButton1_OnClick
strTheInput = Document.Forms(0).Elements(0).Value
Alert strTheInput
End Sub
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<INPUT TYPE="text">
<INPUT TYPE="button" NAME="CommandButton1" VALUE="Click Me">
</FORM>
</BODY>
</HTML>
In this example, neither the form nor the text box has a name.
VBScript places all forms into an array of forms, starting at
number 0; it also places all form elements, such as buttons
and text boxes, into an elements array, again starting at number
0.
To access the contents of this text box, you must know within
which form it resides and the text box's ordinal number within
the form. In this particular example, knowing the number isn't
much of a problem because you have only one form and two elements;
the text box is the first, so it is element 0.
strTheInput = Document.Forms(0).Elements(0).Value
You can now see that it is much easier to name all your forms
and elements and refer to them by name. In fact, to access values
when you send the information to the server, you need names for
your elements anyway.
Look at the form used in the main example in this chapter, which
is shown in the following code segment. Notice that the three
radio buttons have the same name so that you can check only one
button at any one time, leaving the other two unchecked. When
you give the buttons the same name, the browser adds this functionality
for you. The form is constructed with everyday HTML objects and
requires no further explanation:
<FORM NAME="OrderForm">
<TABLE CELLPADDING=20 CELLSPACING=20>
<!--COLUMN ONE ---- OPTIONAL EXTRAS -->
<TD VALIGN=TOP>
<B>Optional Extras</B><BR>
Padded Headrest<INPUT TYPE="checkbox" NAME="option1" Value="Padded Headrest"><BR>
Cup Holder<INPUT TYPE="checkbox" NAME="option2" Value="Cup Holder"><BR>
Shock Absorber<INPUT TYPE="checkbox" NAME="option3" Value="Shock Absorber"><BR>
<!--COLUMN TWO ---- SIZE CHOICE -->
<TD VALIGN=TOP>
<B>Sizes</B><BR>
12 Inches<INPUT TYPE="radio" NAME="choice1" Value="12 Inches"><BR>
18 Inches<INPUT TYPE="radio" NAME="choice1" Value="18 Inches"><BR>
24 Inches<INPUT TYPE="radio" NAME="choice1" Value="24 Inches"><BR>
<!--COLUMN THREE ---- COLOR & BUTTON -->
<TD VALIGN=TOP>
<B>Colors</B><BR>
<SELECT NAME="Colors">
<OPTION>Brushed Aluminium
<OPTION>Black
<OPTION>Blue
<OPTION>Green
<OPTION>Red
</SELECT><P>
<INPUT TYPE="button" NAME="Button1" VALUE="Place your order now">
<TR>
</TABLE>
</FORM>
Take a look at the scripts required for you to interact with each
of the three elements; as you are about to see, each element requires
a very different approach.
To give the correct functionality to an HTML button, you must
give all the radio buttons in a set the same name. This in itself
causes a problem. As you saw previously, the best way to access
an element is via its name, but now you have three controls with
the same name, so what happens when you use the code?
Document.OrderForm.Choice1.Value
The answer is that an error occurs. How does the scripting engine
know exactly which Choice1 you are referring to? In Visual
Basic and Visual Basic for Applications and with the ActiveX radio
control, this confusion isn't a problem because you can specify
an index number to distinguish the control as unique. In fact,
it is regular practice to create a group of the same controls
with the same name distinguished only by an index number. The
HTML radio button has no such indexing feature. What do you do?
Take a look at the following code from the example:
13:'=====================DETERMINE SIZE SELECTION======================
14:blnSize = False
15:For i = 0 to Document.OrderForm.Elements.Count -1
16: If Document.OrderForm.Elements(i).Name = "choice1" Then
17: If Document.OrderForm.Elements(i).Checked Then
18: blnSize = True
19: strTheSize = "Size: " & Document.OrderForm.Elements(i).Value
20: Exit For
21: End if
22: End if
23:Next
24:If Not blnSize Then
25: Alert "You must select a size"
26: Exit Sub
27:End If
Notice that the code reverts to using the elements array. Line
15 uses the element's Count property. The Count
property holds the total number of elements within a particular
form. Because the elements array begins with zero, you subtract
one from the total and start the loop at 0. If your form
has 10 objects, for example, you reference them as Elements(0)
to Elements(9).
The name of the radio button is used in line 16 to check whether
the current element object is the one you want. Don't forget that
going through all the form elements in this way returns every
element, such as checkboxes, buttons, and so on. If the program
finds the name choice1, you know you have the right object.
Notice that you can use Elements(i) as though it were
the object's name and access all the element's properties in the
same way. For example, the following two lines are the same:
Document.OrderForm.choice1.Name
Document.OrderForm.Elements(i).Name
i represents the ordinal number of the choice1
element.
When the program locates one of the three radio buttons, you must
find out whether it is checked, which line 17 evaluates. If the
radio button is checked, line 17 evaluates to True, and
lines 18 and 19 are executed. If the button is not checked, the
loop continues.
Line 18 sets a flag to True, which is used in line 24
to determine whether the user selected any size. If he didn't
choose a size, a warning message displays, and the script's execution
halts. Line 19 copies the value of the checked radio button to
a variable that is used later to get confirmation from the user.
After you find the checked radio button, you know there can be
only one, so any further execution of the loop is a waste of time.
Line 20 jumps out of the loop using the Exit For statement.
The method for determining which checkbox is checked is different
from the method for finding the checked radio button. First, you
must consider that several permutations could be present. The
user could have selected one, two, all, or none of the options.
The following segment shows the code used for the checkbox inspection:
31:'======================DETERMINE OPTIONAL EXTRAS======================
32:strOptExtras = "Options: "
33:intOptQty = 0
34:If Document.OrderForm.option1.Checked Then
35: strOptExtras = strOptExtras & Document.OrderForm.option1.Value & " "
36: intOptQty = intOptQty + 1
37:End If
38:If Document.OrderForm.option2.Checked Then
39: If intOptQty > 0 Then
40: strOptExtras = strOptExtras & "and "
41: End if
42: strOptExtras = strOptExtras & Document.OrderForm.option2.Value & " "
43: intOptQty = intOptQty + 1
44:End If
45:If Document.OrderForm.option3.Checked Then
46: If intOptQty > 0 Then
47: strOptExtras = strOptExtras & "and "
48: End If
49: strOptExtras = strOptExtras & Document.OrderForm.option3.Value
50: intOptQty = intOptQty + 1
51:End If
52:If intOptQty = 0 Then
53: strOptExtras = "No Options Required"
54:End If
The Checked property of the checkbox object returns True
if the checkbox is checked and False otherwise. The first
two lines of code, 32 and 33, initialize the variables used in
this section. As you see, the parts of this section are similar
to each other. A test is performed (lines 34, 38, and 45) to find
out whether the checkbox is checked, and if it is, the value of
that checkbox is concatenated to the string (lines 35, 42, and
49).
A counter (intOptQty) determines whether any checkboxes
are checked. If none are checked, the value of the counter remains
at zero. At various stages (lines 39 and 46), the counter is tested
to determine whether the current checkbox is the first or a subsequent
option. If it is a second or third option, the word and
is concatenated to the string (lines 40 and 47). The counter is
incremented every time a checked checkbox is encountered (lines
36, 43, and 50).
The HTML select object is very straightforward to use and has
several useful built-in properties. It also contains a kind of
options sub-object, which has its own properties.
Here are the main properties of the select object:
- Length returns an integer value of the number of
options declared using the <OPTION> tag within
the <SELECT> block:
intNoofOptions = Document.Form1.MySelect.Length
- SelectedIndex returns an integer value of the index
number (zero is the first list item) of the option the user has
selected:
intColor = Document.OrderForm.Colors.SelectedIndex
The Option object is an array of strings that contains
a list of options defined with the <OPTION> tag.
The first one is always indexed at 0. The Option's
Text property returns a string containing the text entered
in the HTML file directly after the <OPTION> tag.
You can only use it by specifying which option you want to reference:
30:strTheColor = "Color: " & Document.OrderForm.Colors.Options(intColor).Text
In the example, the selected item is determined using the SelectedIndex
property of the select object. This value is then used to return
the text of the option:
28:'======================DETERMINE COLOR SELECTION======================
29:intColor = Document.OrderForm.Colors.SelectedIndex
30:strTheColor = "Color: " & Document.OrderForm.Colors.Options(intColor).Text
Note |
Unlike the ActiveX drop-down list (combo), the HTML version is read-only, which means you cannot add items or change the text in any way after the HTML file is rendered in the browser.
|
The final part of the script builds the message string from the
variables that had values assigned to them in the course of the
selection-checking processes described previously.
When the message string is complete, it is used in a message box
of type 36 (Yes and No buttons and a Question Mark icon), as shown
in Figure 5.2. In a real form, you would make some further decisions
and carry out further processes based on the return value of this
message box, which you collect in the intResponse variable.
Figure 5.2 : The message box asking the user to confirm
his order.
In this chapter, you learned several ways that you can write scripts
to determine the values selected by the users prior to sending
data to the server. You saw how to loop through the form's elements
to find particular controls, and you used a control's properties
to point to the selected option.
You worked entirely with HTML intrinsic objects and saw the hierarchy
of window, document, form, and element. You saw several examples
of the dot notation used to refer to properties of an object.
In the next chapter, you'll see how to programmatically submit
data to the server using VBScript.
Now that you've seen how to use HTML form elements with VBScript,
you can create interactive documents using your current HTML pages
as a base. For further information, see these chapters:
- To learn more about form data and data verification, see Chapter
6, "Checking Form Data."
- Chapter 9 "Making Your Program Flow," describes
For...Next loops and If...Then conditional statements.
- When you're working with strings, read Chapter 7 "Manipulating
Strings."
- For more information about LazeeGeek Computer Users Head Props,
fill in the form!
Q: | Can all the HTML Intrinsic Controls be interfaced with VBScript?
|
A: | Yes. The Active Scripting Object Model (see Appendixes B, "HTML Intrinsic Controls: Properties, Events, and Methods," and D, "Active Scripting Object Model") defines the type and minimum functionality of HTML controls and objects used in an active scripting environment such as MSIE 3.x. It also specifies the properties, methods, and events that each should have. However, each HTML control is slightly different, so what you can do with one control, you might not be able to do with another.
|
Q: | Why would I want to use HTML Intrinsic Controls when I have all these ActiveX controls that perform much better?
|
A: | There are several reasons why you could choose HTML Intrinsic Controls. Suppose you have a complex form that you have been developing and maintaining for some time. Rather than scrap the whole form, you could enhance what you already have by adding some scripting to it. There's also the consideration of download time, which should be much quicker using HTML controls, although all the ActiveX form controls should be immediately available to users of Windows 95. Finally, by using ActiveX controls, you are completely blocking users of Netscape Navigator from your form, whereas if you had used HTML controls, those users would at least be able to use the form (albeit without the scripted functionality).
|