The Subordinate Objects of the Document Object

OK, we’ve covered a lot of Document’s functionality in the last few pages, but we’re not finished yet. We still have some of the most useful things to talk about. Not surprisingly, these are actually objects in themselves. We’ll be talking about the Anchor, Link, and Form objects (as well as their respective collections) and the Location object (which, all by its lonesome self, doesn’t have a collection). All of these objects are generated when the page is parsed, and they reflect the properties of the page currently in the browser.

Like we’ve said, three of the four objects we’ll be talking about here are actually stored in collections. Objects inside collections can’t be referenced in code without the collection being named first in some manner. After covering the objects themselves, we’ll talk about some special cases that can arise when programming with collections. You've already had experience with many ASP collections, like Request.Cookies, and Request.Form, and you can rest assured that using collections on the client is nearly identical—only the names of the collections, the objects, and their properties and methods, are different.

The Link Object

The Link object represents something you’re very familiar with if you’ve ever browsed the web—a hypertext link on a page. The Links collection is made up of Link objects, one for each anchor tag containing an HREF attribute (<A HREF="...">) on the page. We can’t change the links on the current page when browsing, and so, not surprisingly, all the elements of this collection, and their properties, are read-only. The link object has nine properties and two events, but no methods.

Link Object Properties

Guess what? The properties of the Link object (with one addition) are identical to the properties of the Location object we covered earlier. We won’t repeat them here, but if you need to you can refresh your memory a few pages back.

In addition to the eight properties that it shares with Location, a Link object also possesses an additional property called Target. This property is blank unless the link has a TARGET attribute used to refer to a new browser window or frame. For example, the Target property of the following URL is MainFrame:

<A HREF="http://www.mysite.com" TARGET="MainFrame">

Link Object Events

Viewers of our page can do things to links: they can click them or move their mouse over them. The events supported by Link allow us to respond appropriately to these actions.

The Link object has an onMouseOver event that is fired when the user moves the mouse over a link. We can do some cool tricks with links by hooking up code to this event. Since links really don’t have a name per se, it’s easiest to specify the desired behavior in the anchor tag itself:

...
<A HREF="http://bossman" onMouseOver="MyFunc">Bossman<A>
...
...
<SCRIPT LANGUAGE="VBScript">
Sub MyFunc
  Alert "Moved"
End Sub
</SCRIPT>
...

In this example, the combination of the anchor tag’s onMouseOver attribute and the MyFunc subroutine causes an alert message box to be displayed whenever the mouse is moved over the link. Use this for demonstration purposes only. Doing something exactly like this could be annoying to the viewer of our page— they’ll have a hard time clicking on the link if they’re always trying to dismiss a message box first!

Link objects also have an onClick event that works the same as the onMouseOver event, except that it is only fired when the link is actually clicked on. To hook up code to this event we just add an onClick attribute to the HTML for our link, like this:

<A HREF="http://bossman" onClick="MyFunc">Bossman</A>

If we’re not going to do much in the function, we might find it easier to just include our code within the anchor tag, as in-line script. We outlined how to do this in the 'hooking up the code' section at the beginning of this chapter.

The Anchor Object

The Anchor object is one of the simplest objects we’ll see in any object model, and it isn't very useful in most client-side programming. In HTML an anchor is simply an <A> tag. In the object model, we have access to a collection of these tags via the Document object’s Anchors property. Anchor objects have one property, Name, which is set to the NAME attribute of the given tag.

Internet Explorer 3.01’s Anchors collection only includes HTML elements with a NAME property and without an HRef property.

The Form Object

In contrast to the Anchor object, the Form object is supremely useful to client-side programmers. Its properties encompass such information as the current ACTION address, the METHOD, and the encoding for the form. Its sole method and event encapsulate form submission. In addition to the normal properties, each Form object has an Elements collection that provides access to each HTML element (the text boxes, buttons, etc.) on a given form. We’ll cover this very important collection as soon as we finish talking about the Form object itself.

The Form Object Properties

The five properties of Form are Action, Encoding, Method, Target, and Elements. This section talks about the first four properties. These are derived from the opening <FORM> tag. So, like we did with the Location object, we’ll invent a tag and then show the resulting property values. Our tag for this demonstration will be:

<FORM NAME="myForm" ACTION="http://www.mysite.com/search" METHOD="GET" TARGET="NewWindow" ENCTYPE="text/html">
Property Value Description
Action http://www.mysite.com/search Action for form processing (usually a URL)
Method GET Form data submission to server (GET or POST)
Target NewWindow Name of target window to display results in
Encoding text/html* Encoding for the form

* IE 3.01 doesn’t display or allow this property to be set correctly

These properties can be read or set to determine the current form settings, or possibly to change the behavior of the form before it is submitted.

Submit and onSubmit: The Form’s Method and Event

The Form object’s single method (Submit) and event (onSubmit) handle form submission. Calling Submit submits the form, with the same result as a viewer clicking on a Submit button in the form.

As you’ll see in the simple code in this section, and in a detailed example in the next chapter, client-side code can be very useful in performing validation of data entered on a form before the form is submitted. By doing this, we save a trip to the web server and back just to inform a user that they entered invalid data. Keep in mind that this only guarantees that information coming from our page is properly validated and acceptable. It doesn’t actually mean that any data received is OK.

For example, there’s nothing stopping someone from writing an application that sends data to our Web server, and in this case the data will never have seen the validation code in our Web page. The morale of the story is: if it’s extremely important that only certain data ends up in your database, then you'd better check it at the server end too. However, most applications don’t require this depth of protection.

The page below submits the form when the Submit button is clicked, unless the user has entered "no" in the text box—in which case the form is not submitted:

<HTML>
<HEAD>
<TITLE> Form Submit </TITLE>
</HEAD
<BODY>
<H1> Form Submit </H1>
<FORM NAME="myForm" ACTION="http://mysite.com/" METHOD="GET">
   <INPUT TYPE="TEXT" NAME="txtOne">
   <INPUT TYPE="SUBMIT" NAME="sbmTest">
</FORM>
<SCRIPT LANGUAGE="VBScript">
Function myForm_onSubmit
   If Document.myForm.txtOne.Value = "no" then
      myForm_onSubmit = False
   Else
      myForm_onSubmit = True
   End if
End Function
</SCRIPT>
</BODY>
</HTML>

Looking closely at the code on this page, you might notice something odd: the handler for the onSubmit event is a function, not just a normal subroutine. Every other event handler we’ve written has always been a subroutine, so why the change now? The answer is in the way Internet Explorer and Navigator are set up to process the onSubmit event. In this one single case, they look for a return value and act accordingly. If this event returns False, the form isn’t submitted. If it returns anything else, the form is submitted normally.

An alternative to this method is to create a normal (i.e., non-submit) button with an <INPUT TYPE="BUTTON"> tag. In the handler for the onClick event of this button, we perform our validation. We only submit the form, using the FormName.Submit method, when the data meets our requirements. The next chapter includes a more in-depth example of client-side validation.

The Elements Collection

Each Form object has an Elements collection, which represents the HTML form elements inside a pair of <FORM>...</FORM> tags. Any element that can be created with HTML (including objects created with the <OBJECT> tag) can be represented in the Elements collection.

As we’ll see in the next section, it’s important to correctly name the form where the object we’re interested in resides (both in script code and in HTML). If this information is incorrect, the browser won’t be able to find the object we’re talking about, and will give us a rude error message saying that the object doesn’t exist! If we don’t identify the object correctly, as far as the browser is concerned, it doesn’t exist.

Once we have access to the elements of a form, we might want to know how they act. We’ll cover the HTML form elements next.

HTML Form Elements and the Element Object

HTML form elements can be very different. We can create text boxes, buttons, check boxes, and more with HTML. Accordingly it will probably come as no surprise to you, having worked with these elements before, that the properties, methods, and events for these elements are also different. Fortunately, however, similar objects usually have the same properties, methods, and events, making our job of understanding them easier.

Rather than cover how to use each and every one of these elements, and duplicate a lot of code and text in the process, we’ll instead provide a table showing the properties, methods, and events for each object, and some general comments about these characteristics.

For a much more detailed coverage of this topic, check out the Wrox Press book Instant VBScript.

If you’re interested in actual code (and who isn’t?), be sure to take a look at the in-depth examples in the next chapter, and at the code samples throughout this chapter.

Element Properties Methods Events
button, reset, submit form, name, value click onClick
checkbox form, name, value, checked, defaultChecked click onClick
radio form, name, value, checked click, focus onClick
password form, name, value, defaultValue focus, blur, select None
text, textarea form, name, value, defaultValue focus, blur, select onFocus, onBlur, onChange, onSelect
select name, length, options, selectedIndex focus, blur onFocus, onBlur, onChange
hidden name, value None None

Many of these properties will be familiar to you from prior reading and work, but we’ll review them briefly below.

The Element Object's Properties

Fortunately for us, each object has a Name property. If it didn’t, we’d have a hard time referring to the object in code, and the object model wouldn’t be much use to us. Other useful properties include Form and Value. Form returns a reference to the element’s form object, while Value gets or sets the value of the element. While all the elements have a Value property, the actual contents of this property vary depending on the object itself. For example, the Value of a text element is the string in the text box, while the Value of a button is the button’s caption.

The Element Object's Methods

Some combination of the click and focus methods is common to all elements except for the hidden element (which has no methods or events). The click method causes the same result as a user clicking on the object. Calling the focus method of an object moves the current input location, or focus, to the object. For example, the code:

txtOne.Focus

moves the input cursor to the text box object named txtOne. The blur method is the converse of focus; it removes the focus from the current object. Finally, the select method, a feature of the password, text, and textarea input elements, selects the current contents of the object. This has the same effect as if the viewer of the page had clicked and dragged the mouse across the text in the input element.

The Element Object's Events

We’ve already seen one input element event many times: onClick. Each object that has a click method also has an onClick event, where code is placed ready to be executed when the object is clicked. Other interesting events that can be used in a similar way are onFocus (called when the element receives the focus), onBlur (called when the element loses focus), and onChange (called when the Value property of the object changes).

Referencing Objects in Collections

Now that we’ve covered the most important collections in the Document object, it’s a good time to refresh our memory on how collection objects need to be referenced in code. Just like with ASP collections, items in the collections of the browser object model can be referenced one of two ways: by name or by index.

The choice of these collections has a practical aspect: whenever we refer to an object in a form (a very common client-side task) we need to make sure we reference the object correctly. Remember that the browser creates a Form object in the Forms collection for each <FORM> tag on the HTML page, and an item in the Form’s Elements collection for each element in the form. All collections have the additional property Count, which returns the number of objects that are currently held in the collection.

To illustrate this concept, we’ll use the Form and Elements collection. Suppose a page with a single HTML form laid out like this:

<FORM NAME="myForm">
<INPUT TYPE="BUTTON" NAME="btnOne" VALUE="Click Me"><BR>
<INPUT TYPE="TEXT" NAME="txtElement">
</FORM>

After the page is parsed and displayed the Count property of the page’s Forms collection would hold the value one, as the page boasts a single form, named myForm. The Count property of the myForm.Elements collection would be two, because there are two input elements inside myForm.

Why does this matter, outside of knowing how many objects are in a collection? When referring to objects in code, the index numbers of the collections can be used instead of, or in tandem with, the names of the objects. For example, the Action property of myForm could be referred to with this code, which uses the name of the form:

Document.myForm.Action

or with this code, which uses the index:

Document.Forms(0).Action

Note that, while Count returns 1, the collection is indexed from 0 to Count 1.

Similarly, the form’s elements could be named in code like this:

Document.Forms(0).btnOne.Value
Document.Forms(0).txtElement.Value

or by index, like this:

Document.Forms(0).Elements(0).Value
Document.Forms(0).Elements(1).Value    

It’s important to remember that we need to add this relatively long qualifier when referring to input elements (or OBJECTs) inside a form. If we don’t do this, the browser will think we’re trying to refer to a control that’s not on a form, i.e. that we’re talking about a control that’s on the page itself. Using simply btnOne.Value instead of one of the longer lines of code above will cause an Object required error (unless of course an element named btnOne exists outside the form). Without specifying the form that the object resides in, the browser can’t tell what form element we’re talking about.

Form elements or objects created with the <OBJECT> tag that are placed outside of a <FORM> tag should be named without a preceding object reference—they don't belong to any form, and so they aren’t a part of any form’s Elements collection. And because objects are only created when an <OBJECT> tag is encountered while parsing the page, we need to make sure that any <OBJECT> tags come before script code that references them.

© 1997 by Wrox Press. All rights reserved.

Show: