Although HTML pages can be difficult to develop, they are usually very simple to use. The number of things you can do with an HTML page is quite limited. For the most part you simply look at it-read its text, admire its graphics, and, perhaps, listen to the sounds it can play. For many, the Web experience consists of visiting a series of pages without interacting with them. The only interaction occurs when the user selects a link or clicks an imagemap.
HTML forms have gradually changed that model to increase the level of interaction. A form can have a variety of ways of accepting input, including text fields, buttons, checkboxes, and multiple choice selections. In this way, HTML forms are a lot like paper forms. The user fills in the form, perhaps to purchase some item, and then submits the form. This submission process also mimics real life. It is difficult to tell if the form
has been properly filled in, and the time taken for processing the form is often quite lengthy. In the case of HTML, this processing delay occurs because the contents of the form must be sent across the network to some URL, processed there, and then returned to the user. Even the slightest error causes the form to be rejected, so that the form entry must be repeated.
In the navigation category, you can distinguish the following different actions:
In most of these cases the current page will be unloaded, which means it will no longer be visible in any browser window. In several of these cases a new page will be loaded, which means its contents will be displayed in a browser window, perhaps a new one created specifically to display this particular page. Anyone who has used the World Wide Web realizes that selecting a hypertext link may not successfully take you to another. The machine to which that link points may be down, or simply inaccessible. The link may even be dead, meaning that it does not point to a valid destination. Selecting a dead link often unloads the current page, but doesn't load a new page. Most browsers display a blank page or post an error message. You may or may not be left on the current page, depending on the type of error and the browser being used. A sample error alert from Netscape is shown in fig-ure 3.1.
Figure 3.1 : Attempting to access a non-existent URL results in an error message on some browsers.
There are two additional events that are vaguely related to navigation. These events are the following:
Button Elements in Forms Buttons come in five varieties, as follows:
Simple buttons are defined using the HTML <INPUT TYPE="button">. Checkboxes define options, which are either off (not checked) or on (checked). These are created using an <INPUT TYPE="checkbox"> directive. Radio buttons use the <INPUT TYPE="radio"> directive, and permit the user to select exactly one of a set of choices. Submit buttons and reset buttons are very special. Submit buttons, created by <INPUT TYPE="submit">, are used to end input operations on a form. When the submit button is pressed the contents of the form are packaged and sent to the URL target specified in the ACTION attribute of the <FORM> definition. Reset buttons bring the form back to its initial state, wiping out any input the user has performed; they are specified as <INPUT TYPE="reset">. Figure 3.2 shows a simple HTML form with all five button types; it was generated by the HTML file allbut.htm.
Figure 3.2 : All five types of HTML buttons have corresponding
Text Elements in Forms There are three types of text items possible within an HTML form, as follows:
Single line text fields are created with an <INPUT TYPE="text"> directive. Any text you type in a text field is displayed as you type it. This behavior is known as echoing the input. Single line text fields that are created using <INPUT TYPE="password"> do not echo their input. Multi-line text fields are created with the TEXTAREA tag, and are usually called textareas. An HTML form showing all three types of text elements is shown in figure 3.3, created from the file alltxt.htm on the CD-ROM. Interacting with text is more complex than interacting with a button. There are more things you can do with text. You can click in the text field, enter text, edit text, select text, and decide you are finished with the text and move on.
will be familiar to anyone who has ever used a windowing system.
It defines four events that are associated with text fields and
textareas, but not passwords fields-change, select,
focus, and blur. The first two should be self-explanatory.
The change event is generated whenever any text is changed,
and the select event is generated whenever text is selected.
Selecting text is more than simply clicking in the editable text
field or textarea. It means actually highlighting a portion of
the text with the mouse.
focus and blur are a little more involved. A text field or textarea is said to have focus when it is currently accepting input typed at the keyboard. Clicking anywhere inside a text item is certain to give it focus, and simply moving the mouse over the text field may do so as well. blur is the opposite of focus. Blur occurs when the text item no longer has focus. This may happen because some other item now has the focus, or because the focus has simply been lost. You will notice that if you position the mouse over a graphic (other than an imagemap), you can type until your fingers are sore, but nothing happens. This is a case where nothing has focus.
In the most general sense, every Web page is constructed from HTML statements that divide the page into two parts: the <HEAD> and the <BODY>. The HTML directives within the context of the <HEAD> give information about the page, while those in the <BODY> make up the page itself. In most simple HTML documents the <HEAD> usually contains only the <TITLE>. It can also contain a BASE tag which specifies a pathname that should be used to resolve relative HREFs within the document, and one or more LINK tags, which indicate the relationship of this document to one or more other documents, such as the browser's home page.
<SCRIPT LANGUAGE="LangName" [SRC="URL"]>
Netscape Navigator 2.0 does not yet support the SRC attribute. This feature has been promised for version 2.1.
If the SRC attribute is not given then it is expected
that all the code between <SCRIPT> and </SCRIPT>
is the script source itself. In the glorious future, when the
overwhelming majority of browsers understand the SCRIPT
be given literally. Until then it is recommended that source included
between <SCRIPT> and </SCRIPT> be
enclosed within the HTML comment delimiters <!--
function is shown in listing 3.1.
a Single Function
Use of HTML Comments The function in listing 3.1 does not do much; it merely uses the alert() function to pop up a warning dialog box with its argument as the message. Presumably this function is the click event handler for a button you don't want the user to press. The important thing to notice about this simple example is the paradoxical, but important, use of HTML comments. The entire script body is enclosed with a comment, and the comment close --> is also paired with a second, seemingly redundant, comment start <!-- on the last line. At present, you should structure your script according to the following rules:
You should use this magic incantation not because it makes sense,
a SRC URL should also follow these rules, as if it had literally
been included in the <SCRIPT> block. Note also
between <SCRIPT> and </SCRIPT>.
In this case, the URL referenced by the SRC attribute
HTML comments are one of the least conforming areas of HTML. Most browsers deviate a little from the HTML standards, and some deviate a lot. The preceding comment rules may change in the future, and may be implemented differently on different browsers.
Dynamic binding has several consequences. In the first place,
if the function dontclickme() is never called, then it
can contain all but the most hideous syntax errors and they will
never be found. If dontclickme is the event handler for
a button, and no one ever presses the button, its problems are
never exposed. Even if dontclickme() is absolutely perfect,
but the event handler is erroneously declared to be a function
named noclickme(), this mismatch will not be detected
will only then try to find a function named noclickme().
It will fail, and an error will result. Dynamic binding is often
called runtime binding or late binding because the
attempts to run the code.
Listing 3.2 ex32.htm An Illustration
of Dynamic Binding
Event handler declarations look exactly like ordinary HTML attributes. Each attribute name begins with the word on and is followed by the event name, so that onClick is the attribute that would be used to declare an event handler for the click event. The full declaration of an event handler looks like
Attribute names are not case-sensitive, following the usual HTML convention. It is good practice, however, to use the coding style shown in the preceding line of code, with on in lowercase and the event name with an initial capital. This helps to distinguish it from other attributes, which are often fully capitalized.
<INPUT TYPE="button" NAME="mycheck" VALUE="HA!" onClick="alert('I told you not to click me');">
This has two disadvantages. First, it tends to lead to very long
HTML statements. There is very little you can accomplish in only
a few characters. If you have hundreds of characters between the
opening (<) and the closing (>) of an HTML
statement it will almost certainly be very hard to read, and,
if it is too long, may cause your browser to choke. It is also
not modular. As you add event handlers for different HTML elements,
you may well find that there is a lot of common code. Each of
the button handlers might use a variation on the same code. Such
rather than being repeated in several places.
Can Be Shared by Several Event Handlers
You now know how to declare event handlers in general. The next
section shows exactly which handlers can be associated with specific
HTML tags, and gives various examples of how these event handlers
<BODY onLoad="loadfunc()" onUnload="unloadfunc()">
The onUnload="unloadfunc()" attribute declares an event handler that is invoked whenever the page is unloaded. This happens when the user executes any action that brings up a new page in the same browser window. An unload event does not occur if a new page is opened in a new window. Even if a new page is not successfully loaded, the current page is still unloaded, and the unloadfunc is called in that case. An onUnload event handler can be used to ensure that there are no loose ends, and to perform any cleanup necessary. For example, if the user has filled out a form, but has failed to press the Submit button, the onUnload handler should inform the user of that fact. It could even submit the form itself based on the user's response. Note that both the onLoad and onUnload handlers are optional.
There is one final document level event handler, although it is
not associated with the BODY tag. Any HTML link can declare
an event handler for the mouseOver event, which occurs
when the user places the mouse over the HREF of that
link. This can be used to achieve a visual effect, or to perform
some special processing before the user actually tries to access
the link. Listing 3.4 shows a slightly fanciful example. This
code can be found in the file ex34.htm on the CD-ROM.
Listing 3.4 ex34.htm Using the mouseOver
Event to Mediate Access
This HTML creates a page with two elements-links to the fictitious home pages of the countries Zzland and XYville, and sets up a mouseOver event handler for those links. Note that the event handler function warnthem is called with an argument this. The special keyword this is used to refer to the current object. When the warnthem function is called, its parameter lnk is filled in with the object that represents the link over which the mouse just moved.
Statement 2 extracts the hostname part of that object, which in this example could be either home.std.zz or home.xyzzy.xy, depending on where the mouse is located. The next three statements use some of the string object functions (see "String Content Methods," in chapter 4) to tear off the last part of this fully qualified hostname, namely zz or xy, and save it in the variable domain. This variable is then tested against zz in statement 7. If the test passes then an alert is put up to warn the user that the connection to the zz home page will take longer due to slow modems. Links can also have click event handlers, so this code can be modified not only to warn the user, but also to abort the connection, if necessary. The result of placing the mouse over the Zzland link is shown in figure 3.6.
The FORM tag is used to begin the definition of an HTML form. It includes attributes from the METHOD to be used in submitting the form, the ACTION to be taken, and may also include a single type of event handler attribute, the onSubmit attribute. The syntax for a FORM tag is the following:
<FORM NAME="formname" ... onSubmit="submithandler()">
Put event handler attributes last on the attribute list of an HTML tag. This makes them easy to find and modify during debugging.
The onSubmit handler is invoked when the form's contents
are about to be submitted. This is a top level action that applies
to the entire form. It is also possible to specify an onClick
action on the Submit button in a form, as you shall see later
in the section, "Button Click Events." The natural use
of an onSubmit handler is to validate the contents of
a form. The submission proceeds if the contents are valid, and
is canceled if they are not.
If you return false in an onSubmit event handler using UNIX version 2.0 of Netscape Navigator, it does not cancel the submit.
Listing 3.5 (file ex35.htm on the CD-ROM) shows a very simple form with a single element, an editable text field. The value of the field is supposed to be a number between 1 and 9. The submit handler function checkit is called when the form is submitted. It validates the user-entered quantity and acts accordingly.
Listing 3.5 ex34.htm Form Content Can
Be Validated Using an onSubmit Handler
The first INPUT tag establishes an editable text field named mytext which can hold up to 10 characters, and which will be initialized to the string "1". The second INPUT tag puts a Submit button just below the input text field. Neither of these INPUT statements have any handler attributes, although they could. What happens next?
The checkit function does two somewhat obscure things. In statement 2, it sets the local variable strval equal to the value of document.myform.mytext.value. We know from the "Functions and Objects" section of chapter 2 that the right side of this expression must be an object reference-in fact, a reference to an object within an object within an object. It is reasonable and correct to assume that the myform subobject corresponds to the HTML form named myform within the current document, and that the mytext subobject corresponds to the HTML editable text field named mytext inside myform. This windy construct transfers the value of that text field into the local variable strval. In statement 3, an attempt is made to convert this string to an integer using the built-in function parseInt. The putative integer is stored in intval.
If the text field was out of range then the else pathway in statement 6 is taken. Note that parseInt returns 0 if its argument cannot be parsed as an integer. This means that if the user entered "five" in the text field rather than "5" the value of intval will be 0, and the else clause will be taken. Statement 7 puts up an alert dialog box telling the user that the value was out of range. It contains the string representation of the value. This is useful since the alert dialog box may be inadvertently positioned over the text input field. Finally, statement 8 returns false, indicating that the submit operation should not complete. The outcome of entering a value that is out of bounds is shown in figure 3.7.
In this particular case it is important to give the mytext
text field an initial value of 1. This ensures that if the user
clicks the Submit button without altering that text field it will
have an acceptable value, and the form will be submitted. In many
cases, just the opposite is true. The whole point of a catalog
order form is to persuade the user to enter critical information,
such as his name and e-mail address. In this case, it's a good
idea to initialize the text field with a deliberately invalid
value, so that if the user hits Submit without typing anything
the form is not submitted. Chapters 6, "Interactive HTML
Objects," and 16, "Creative User Interaction,"
provide several more sophisticated examples of customized user
Always give the user meaningful feedback on inappropriate input or other error conditions. Indicate why and where the error occurred, not just that an error occurred. Be brief, but specific. N
Almost all form elements may have one or more event handlers.
The type of event handlers permitted on a given element depends
on the type of element itself. You have already seen the linkage
between events and HTML entities in figure 3.4. Broadly speaking,
buttons can generate click events, and text and select
items can generate focus, blur, select,
and change events. The one potentially confusing aspect
of this organization of events is that selection lists cannot
select event. This is because they have no editable text. We will not consider all possible events in this chapter, only a pithy subset.
There are two important exceptions to the rule that all form elements can have handlers. The first exception applies to hidden items, those with <INPUT TYPE="hidden">. Since they cannot be seen, they cannot be changed by the user, and therefore cannot generate events. The second exception applies to individual OPTION elements within a SELECT selection list. The SELECT tag itself may have attributes declaring focus, blur, and change handlers, but the OPTIONs may not gen-erate their own events. Any acquisition or loss of focus, and any change in the item(s) that have been selected applies to the whole list, not to an individual element.
Button Click Events All button types within an HTML form can have click event handlers by adding an onClick attribute to their <INPUT> declaration. Simple buttons with a TYPE attribute of "button", "reset", or "submit" merely signal that they have been pressed. (Recall that the act of submitting a form may also be caught using an onSubmit handler attached to the <FORM> declaration.) Checkboxes and radio buttons also have values. Checkboxes and individual radio buttons can be asked if they are on or off. A group of radio buttons can also be asked for the unique index of the button currently checked.
One very common problem in HTML forms design is the issue of conflicting options. Users are often presented with a variety of different choices, which may even be spread out over more than one HTML form. Some combinations of choices may be invalid or dubious. Unfortunately, in standard HTML there is no way to perform input validation of this kind without actually submitting the form and asking the ACTION URL if that particular combination is acceptable.
Listing 3.6 ex36.htm Values of Different
The <BODY> of this page sets up a two-choice radio button named payment, and a checkbox named insurance. The first button is selected, and the checkbox starts off unchecked. The radio button group has the function insok as its click event handler. Whenever either of the buttons is clicked the insok function is called.
In statements 2 and 3 insok fetches the current value of the second radio button named payment. Note that payment actually denotes the entire group of buttons, not any single radio button, so that you must use the array reference payment in order to refer to the second button (0 based indexing is used). That value is stored in the boolean variable isgold. The variable insok gets the state of the insurance checkbox, which is also true if it is checked and false if it is not. A compatibility test is now performed in statement 5. If the radio button group indicates payment in gold bullion, but the insurance button is not checked, then a confirmation dialog box is put up using the confirm() function in statement 6.
The confirmation dialog box has OK and Cancel buttons. If the
user presses OK, the function returns true; otherwise
it returns false. The return value is tested in statement
7. If it was true, then the user does want insurance,
and the method function value of the checked property of the
myform.insurance object is set to true. Without
worrying too much about what methods and properties really mean
just yet, it is easy to infer that this assignment statement has
the same effect as a click of the insurance button. That checkbox
is now checked.
I modified the code shown in listing 3.6. I added another group of radio buttons to collect information about the user's income level, with its own event handler doinc(). I would like to force the insok() function to be called from the new event handler. Inside doinc() I have a statement
This click() function is supposed to cause the insurance checkbox to be checked, but the doins() handler is never called. Why?
Text Edit and Selection Events HTML text <INPUT> fields with a TYPE attribute of "text" may declare event handlers for any combination of the four text events: focus, blur, change, and select. Multi-line text input items created with a TEXTAREA tag may also have these handlers. Selection lists created with <SELECT> can generate all these events except select.
The focus event is generated when the text item of a list element gets the input focus, usually as a result of a mouse click. Tabbing through form fields also moves the input focus. The blur event is generated when an item which had focus looses it. The change event is generated whenever something changes. In a text item this results when any new text is entered or existing text is deleted. In a selection list it happens whenever a new selection is made, even in a list that permits MULTIPLE selections. The select event is generated when the user selects some text, usually by click-and-drag or double-click operations with the mouse. The select event is almost always accompanied by a visual cue, usually by the selected text becoming highlighted or changing color.
These events can be used to obtain very fine control over the content of text or selection list items. The most common application is to use the change or blur events to ensure that a text field has an appropriate value. If you ask the user to enter her birthdate, for example, and provide separate fields for the month, day, and year, you will almost certainly want to make sure that the value of the day field is a number between 1 and 31. You might even go to greater lengths, and limit the day field's value based on the value of the month field. In any case, you want to avoid erroneous input such as "bleen." Text events can also be used to coordinate the values coming from multiple form elements, as we saw in listing 3.6.
The modulus operandi of this example should be becoming familiar to you now. If the user types or clicks in the textarea nothing happens. When he leaves the textarea and clicks elsewhere a blur event is generated and the handler function hasE invoked. This function gets the contents of the textarea into a local variable named thestr (in statement 2) and then uses one of the string functions to convert it to lowercase (statement 3). This saves a little time, as the function won't have to test for the presence of both e and E. The new lowercase string uthestr is tested against the empty string in statement 4. If there is no text the function returns without complaint.
If there is some text, but it has an e the user is reprimanded in statement 8. If there is no e but the text has less than 20 characters the user is encouraged to try a more ambitious work in statement 11. If the text is long enough and has no e then the user is praised in statement 13. Of course, there is nothing preventing the user from entering gibberish such as zzzzzzzzzzzzzzzzzzzzzzzzz and being congratulated anyway. Much more sophisticated checking would be necessary to ensure that the input was actually a sentence.