Putting Your Best HTML Interface Forward

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Most of the HTML forms that I’ve seen are not very usable. Is it even possible to create a user-friendly and efficient keyboard interface with HTML? To turn a typical Web form into a real data-entry application, you’ll need to organize the fields logically and provide navigational keys, data validation, error reporting, and help text; you’ll also need to avoid anything that requires the mouse for data entry. This article explores how you can do just that.

The FIELDSET

Organizing fields in related groups helps minimize distraction and improve productivity. The HTML FIELDSET tag does the job in a snap. Check out Figure 1; the groupings are obvious. Each FIELDSET has an associated LEGEND or group heading. A single letter is underlined to identify an accelerator key for each group. Pressing the Alt key in combination with the indicated letter causes the focus to jump to the first field in the group, making it easy to move around the screen. I’ve used Cascading Style Sheet (CSS) classes, which align things visually and prevent the browser from inserting line breaks between a label and its field while still allowing it to adjust for varying display resolutions and window sizes. Figure 2 shows how the first FIELDSET is constructed. Note the LEGEND element immediately following the FIELDSET tag. One of the characters is within a SPAN that specifies class=”accesskey”. This CSS class instructs the browser to underline the text for the benefit of the user. The same character is specified as the ACCESSKEY attribute of the HTML element that will receive focus, so the browser will know what to do. The default visual attributes of the FIELDSET tag are also specified in the CSS to produce the 3-D panel appearance.

Next, in Figure 2, Section B, I’ve shown a LABEL element. A LABEL identifies the relationship between the text describing a field and the field element itself. Here, both the text and the field are coded inside the LABEL, but that’s not required. The FOR attribute of the LABEL identifies the relationship to the browser. According to the HTML
4.01 specification, it’s only necessary to include a FOR attribute if the element is external to its LABEL. However, Microsoft Internet Explorer 5.5 will not process the access key unless the FOR attribute is present.

The LABEL tags also specify a CSS class, which prevents line wraps from being inserted between the label and field. To see how this works, download the example code, double-click the survey.html file, and resize the browser window. The effect is especially noticeable in the Our Performance section, where each LABEL and its control will reposition as the window size changes.

In Figure 2, Section C, a SELECT element is used to produce a drop-down list containing acceptable values for a salutation. Value selection can be done with the up and down arrow keys or by typing the first letter of the desired option. The VALUE attribute of the selected option will be returned to the server when the form is submitted. SELECT elements work well when there are a small number of allowed values for a field. When there’s a long list of options, it’s often more efficient to allow the user to key the value and validate it before the form is submitted. If the validation fails, a list of acceptable values can be displayed in a pop-up window. That’s how I’ve implemented both the state/province and country code fields.

At the bottom of Figure 2, Section D, is the specification of an INPUT element, which is similar in function to a normal green-screen data entry field. Notice that most elements have an ID attribute. While ID attributes are optional, when they are present, uniqueness is required. No two ID attributes in the same document may have the same value.

Tab Indexes

Reaching for the mouse can be a big distraction. A user should be able to navigate through the form without clicking. A tab index is nothing more than a numeric value defining the order in which the various controls on a page will receive focus. Each time the user presses the Tab key, focus advances to the control having the next greater tab index value. Pressing Shift-Tab moves the focus back to the previous control. Referring to Figure 2 again, notice that each data entry element has a TABINDEX attribute defining this order. TABINDEX attributes may be assigned any numeric value between 0 and 32,767. I usually assign them by 10s, so that I can insert new controls without renumbering the entire page.

Input Fields

As mentioned above, the INPUT element is used to define a field. You can specify a maximum field length in characters if you like, with the SIZE attribute like this:

tabindex=”30” size=”1” type=”text”>

You can add a VALUE attribute to set the initial field value, if necessary.

Text Areas

As with any data entry application, sometimes it’s necessary to allow the user to enter unformatted text. This is illustrated in the Tell Us section of the survey form. A TEXTAREA element is nothing more than a multi-line text box. It’s specified like this:

The closing TEXTAREA tag is placed immediately after the closing bracket of the opening tag, with no intervening space. Anything between the opening and closing tags, including white-space, will be the initial value of the control. The ACCESSKEY attribute allows the user to jump to the text area with a single Alt-T key-press.

Buttons

It’s probably obvious, but buttons are the interface elements that allow a user to execute predefined actions, such as submitting the data on a form, clearing it, or executing a script. There are two buttons on the survey page. The OK button looks like this:

It has a TYPE attribute value of SUBMIT. In Internet Explorer 5.5, a submit button is the default control on the form. This means that when focus is not within a control that captures the Enter key-press event, pressing Enter does the same thing as clicking the button. Netscape Navigator 6.1 doesn’t treat the SUBMIT button as a default. This behavior is not mandated by the HTML 4.01 specification, so it’s at the discretion of the browser provider. I have added an ACCESSKEY attribute to my OK button. Even if the Enter key doesn’t work, there’s still a convenient way to activate the button from the keyboard. As you would expect, the default action of any submit button is to submit a form.

Two other TYPE attribute values, RESET and BUTTON, are valid within the BUTTON element. When a button with the RESET attribute is activated, it causes all of the controls on the form to reassume their initial values. The Cancel button on the survey form is a RESET button.

There’s no default action for BUTTON elements with a BUTTON attribute. These controls are used primarily to initiate client-side scripts.

The same three button TYPE attributes may also be specified for the INPUT element. They work the same way as the BUTTON element, except that the button text is specified as a VALUE attribute instead of as a text node (between the and tags). Markup isn’t allowed in attribute values, so you can’t include things like the SPAN element that I’ve used to underline the button access keys. The INPUT button types also include IMAGE, a graphical button, which will accept an SRC attribute, identifying the file that contains the image. Netscape Navigator 6.1 does seem to render INPUT buttons marginally better than it does BUTTON elements, so if you’re concerned about browser coexistence, you might want to consider using INPUT.

Other Control Types

In addition to TEXT and the various flavors of button, the INPUT element also supports TYPE attributes of PASSWORD, CHECKBOX, RADIO, FILE, and HIDDEN. I’ve used some check boxes in the Products section of the survey form, so you have an example of how to use that. The other types are fairly self-explanatory, except that the FILE type allows the user to upload a local file to the server, and when using a group of RADIO buttons, the browser will ensure that all but one of the radio buttons in the group sharing a common NAME attribute value are not CHECKED. Notice that I said NAME and not ID. Names are not required to be unique, but IDs are. You can read about these and all the other HTML elements in the official specification at www.w3.org/TR/html401/.

Context-sensitive Help

Since there isn’t a nonproprietary way to capture function keys on a Web page, I’ve chosen to emulate the Microsoft Windows What’s This style of pop-up help instead of using the F1 key. When the user clicks the question mark (?) in the upper right corner of the survey page, the question mark and its container change color as a visual indication of state change, and the mouse cursor changes to a help pointer (an arrow with a question mark next to it). When the page is in whatsThis mode, clicking on any object on the page will cause a window-like help display to be shown. Clicking an empty area will usually display a general help page for the area. If no help text exists for the empty area, the page state is simply reset to text-entry mode. Once the help window is visible, the question mark icon reverts to its normal state, and clicking anywhere outside the pop-up window itself will cause the window to disappear.

In order to accomplish this, I defined ID attributes for virtually all of the HTML elements on the page. The associated scripts are shown in Figure 3 (page 73). At Section A, the initialization script runs when the page is loaded. It executes function getElements(), at Figure 3, Section B. The getElements() function retrieves a reference to the BODY element, stores it, and calls function processElements() in Figure 3, Section C, passing a reference to the BODY, which is the parent element of everything visible on the page. Function processElements() traverses the document tree, calling itself recursively in order to process nested elements. It stores a reference to each element in the nodes array. Doing this up front makes it unnecessary to search the document each time whatsThis mode is activated or deactivated.

Back at Figure 3, Section A, the initialize() function then calls setClickEvents(), which installs a click event handler for each element. Here, I need to briefly visit the issue of browser interoperability. The survey page will execute in either Microsoft Internet Explorer 5.5 or Netscape Navigator 6.1. Internet Explorer does not fully implement the Document Object Model (DOM). Navigator 6.1 implements it almost completely. The setClickEvents() function illustrates one way to handle user agent (browser) incompatibilities. I’ve taken the browser-specific code and segregated it in file javascript/browserspecific.js. This file contains the logic required to determine which browser has requested the page and install references to the appropriate browser-specific functions. The routines in the main page don’t need to know anything about user agent differences. This little magic trick happens when the page is loaded:

if (is_ie5_5 || is_ie5) {
setClickEvents = ieSetClickEvents;
} else {
setClickEvents = nsSetClickEvents;
}

When the initialize() function executes setClickEvents(), it’s really calling either ieSetClickEvents() or nsSetClickEvents(), depending on the requesting browser.

The Boolean variables is_ie5_5 and is_ie5 are set by main-line code at startup in a routine provided by Netscape. This code’s in the javascript/browserspecific.js file and is freely distributable. There are several other function assignments in this initial section that aren’t shown. I’ll mention some of them as I look at the rest of the scripts.

Returning to Figure 3, Section A, the initialize() script finishes up by setting focus to the personal_salutation SELECT element shown in Figure 2, Section B. It’s the first data input control in the Personal Information section of the form. Initialize() then sets the mouse cursor of the whatsThis element (the question mark icon) and the two buttons to pointerCursor, which is the little hand cursor commonly associated with HTML links. The value of pointerCursor is set in javascript/browserspecific.js. Internet Explorer 5.5 doesn’t use the correct name for this cursor, so the variable contains the value that’s expected by whichever browser is displaying the page.

When an object on the page is clicked, the click event handler that was just installed is executed in Figure 3, Section D. If the page is in whatsThis mode, the ID of the object that received the click is used to identify the appropriate help text. Where more than one object needs to display the same help text, I’ve appended a unique character to the ID value. (Remember, IDs must be unique.) The onClickHandler() script checks for this situation by

seeing if it has help text for the current ID. If it doesn’t, it removes the last character from the ID and tries again. The help text itself consists of fragments of HTML stored in an associative array named popText, in file javascript/surveyhelp.js. Notice that this script specifically looks for (and ignores) clicks received by the pop-up window or a child or grandchild of the pop-up window. If the script didn’t do this, you wouldn’t be able to click a link in the window without making the pop-up disappear.

If the page is not currently in whatsThis mode, or the element that received the click is the BODY, or it can’t be identified for whatever reason, onClickHandler() hides the popup window and executes the resetCursor() function shown in Figure 3, Section E.

The resetCursor() function checks to see if the current cursor style is whatsThis (the help cursor). If it is, the script processes the nodes array and resets the cursor style of each node to default. Since setting and resetting the cursor style for everything on the page is rather processor-intensive, the script tries to conserve CPU cycles by not doing anything if the current cursor style is not whatsThis.

Browser Interoperability

As I mentioned briefly, Microsoft does not completely implement the DOM standard in Internet Explorer 5.5. It uses the older event model and still contains some vestiges of the prestandard DOM, which I assume will continue to be supported for backward compatibility. Netscape, on the other hand, has almost completely implemented the DOM standard in Navigator 6.1, but there are a few very significant problems. There is no backward compatibility for earlier versions of Navigator, and the DOM event implementation is very buggy and virtually useless. The Event timeStamp is not unique, and the currentTarget, target, and eventPhase properties are unreliable. Sometimes currentTarget matches the object that received the original mouse click multiple times for a single event, and sometimes it never matches the object at all. Sometimes the eventPhase property never returns AT_TARGET, and sometimes it returns AT_TARGET multiple times. There is, presently, nothing in the Netscape Event object that can be used to reliably determine when to take action, so although Netscape gets high marks for implementing the DOM, without a reliable Event, usability is severely compromised.

Microsoft renders graphical elements and supports CSS in Internet Explorer 5.5 much better than Netscape does with Navigator 6.1. Many of the CSS alignment and sizing attributes are simply ignored by Navigator, while Internet Explorer renders them flawlessly—or at least only requires minor hacks to achieve the desired result.

At the end of the day, while the survey.html page works in both Internet Explorer
5.5 and Netscape Navigator 6.1, it works and looks a lot better in the Microsoft browser, with its more compliant and sophisticated graphic rendering and its older, but more reliable, event model.

What Else?

Obviously, there’s quite a lot that I can’t cover in this limited space. The Customer Satisfaction Survey is a complete HTML form implement-ation, with state/province and country code pick-lists, field validation, error field highlighting, error summary reporting, form submittal, and even a submittal feedback page. Download the example project from www.midrangecomputing.com/mc and try it out. Examine the scripts, and liberate any bits that you like. Maybe you have some ideas or methods that I haven’t thought of. If so, I’d appreciate hearing from you.

REFERENCES AND RELATED MATERIALS

• Cascading Style Sheets, Level 2 CSS2 Specification Web site: www.w3.org/TR/RECCSS2
• Document Object Model Events Level 2 Web site: www.w3.org/TR/DOM-Level-2- Events
• HTML 4.01 Specification Web site: www.w3.org/TR/html401
• The online home of Scott Andrew LePera, Web developer: www.scottandrew.com/index.php (This site offers examples of some of the techniques discussed in this article.)

Figure 1: Rocket science can be functional.


Putting_Your_Best_HTML_Interface_Forward06-00.png 494x345




 Personal

>Information 

Name:



  

First:
tabindex=”20” type=”text”>

...




Address:

tabindex=”50” type=”text”>



...



A

B

C

D

Figure 2: Organize the page with fieldsets, labels, and CSS.


/* ============================================================

Declare globals
============================================================ */

var whatsThisMode = false;
var cursorStyle = ‘default’;
var curElem = 0;
var nodes = null;
var refocusToObj = null;
var helpBackgroundColor = ‘#ffffe0’;
var activeWindowColor = ‘#ffffff’;

/* ============================================================

Initialize values after page load
============================================================ */

function initialize() {
getElements();
setClickEvents();
setFocus(survey.personal_salutation);
document.getElementById(‘whatsThis’).style.cursor

= pointerCursor;
document.getElementById(‘buttons_ok’).style.cursor

= pointerCursor;
document.getElementById(‘buttons_cancel’).style.cursor

= pointerCursor;}

/* ============================================================

Retrieve and stores references to all interesting document
elements for use when setting and resetting the help cursor
============================================================ */

function getElements() {
curElem = 0;
nodes = new Array();
nodes[curElem++] = document.getElementsByTagName(‘BODY’)[0];
processElements(nodes[0].childNodes);

}

/* ============================================================

Helper function for getElements
Uses recursion to examine all elements and
loads the nodes array
============================================================ */

function processElements(elemArray) {
var i = 0;
var id = undefined;
var nodeName = undefined;
var nextLevel = null;
var length = elemArray.length;

for (i=0; inodeName = elemArray[i].nodeName;
if (nodeName.substr(0,1) != ‘#’) {
id = elemArray[i].id;
}

if ((id != ‘whatsThis’) && (id != ‘popup’)

&& nodeName != ‘#text’) {
nodes[curElem++] = elemArray[i];
nextLevel = elemArray[i].childNodes;
if (nextLevel.length > 0) {
processElements(nextLevel);
}

}

A

B

C

}

}

/* ============================================================

Process mouse click events
============================================================ */

function onClickHandler(evt) {
var obj = getEventObject(evt);
var id = obj.id;
var parentId = undefined;
var grandParentId = undefined;
var tagName = obj.tagName;
var helpText = undefined;
var popupClientArea = null;
var popup = null;

if (atTarget(evt)) {
cancelEvent(evt);
// Ignore the error if there is no parent or grandparent
try {

D

Figure 3: A little JavaScript makes it work. No alchemists need apply.



parentId = obj.parentNode.id; }

grandParentId = obj.parentNode.parentNode.id;
} catch (e) { }

if ((whatsThisMode) && (tagName != ‘BODY’)

&& (tagName != ‘FORM’) && (id.length > 0)) {
helpText = popText[id];
if (helpText == undefined) {
id = id.substr(0, id.length - 1);
helpText = popText[id];

}

if (helpText != undefined) {
whatsThisMode = false;
popup = document.getElementById(‘popup’);
popup.style.left

= ((getDocumentWidth() - 350) / 2) + ‘px’;
document.getElementById(‘popupTitle’).innerHTML

= ‘Customer Satisfaction Survey Help’;
popupClientArea

= document.getElementById(‘popupClientArea’);
popupClientArea.style.color = ‘#000000’;
popupClientArea.style.backgroundColor

= helpBackgroundColor;
popupClientArea.innerHTML = helpText;
popup.style.visibility = ‘visible’;

// Perform browser specific hacks
fixDisplayAnomolies1();

if (refocusToObj == null) {
refocusToObj = obj;
}

resetCursor();
return false;
}

if (obj.tagName == ‘BODY’

|| (id.substr(0,5) != ‘popup’
&& parentId.substr(0,5) != ‘popup’
&& grandParentId.substr(0,5) != ‘popup’
&& !whatsThisMode)) {
document.getElementById(‘popup’).style.visibility

= ‘hidden’;
if (refocusToObj != null) {
setFocus(refocusToObj);
refocusToObj = null;

}

} else {

}

whatsThisMode = false;
resetCursor();
return true;

}

}

/* ============================================================

Reset the mouse cursor after help lookup.
Pass all other clicks through for default processing.
============================================================ */

function resetCursor() {
var i = 0;
var id = ‘’;
var obj = null;
var whatsThisNode = document.getElementById(‘whatsThis’);
if (cursorStyle == ‘whatsThis’) {
cursorStyle = ‘default’;
for (i=0; iid = nodes[i].id;
if (id.length > 8 && id.substr(0,8) == ‘buttons_’) {
nodes[i].style.cursor = pointerCursor;
} else {
nodes[i].style.cursor = ‘default’;

}

E

}

whatsThisMode = false;
whatsThisNode.style.color = ‘#0000ff’;
whatsThisNode.style.backgroundColor = ‘#d6d3ce’;
}

}

Figure 3 (continued)



BLOG COMMENTS POWERED BY DISQUS