Cooking with JavaScript & DHTML

Editor's note: This sample recipe is the first of six we've excerpted from JavaScript & DHTML Cookbook. We'll be running one per week over consecutive weeks so check back to this space often for recipes that cover arrays and objects; browser feature detection; style-sheet management; and HTML elements positioning. Today's recipe is from Chapter 8 on "Dynamic Forms."

Recipe 8.12: Auto-Tabbing for Fixed-Length Text Boxes

NN 4, IE 4

Problem

You want to advance the text cursor from one field to the next in a sequence of
fixed-length boxes.

Solution

The following form excerpt requests the customer's
credit card number in four segments of four characters each:

The onkeypress event handler for each field restricts entry to numerals, while the
onkeyup event handlers invoke the following
function, which advances focus to a named form field after a set
number of characters:

In this example, the final field does not advance focus, but you can
add an onkeyup event handler that passes the name
of the next form field to the autofocus( )
function.

Discussion

Many variations on the themes presented in the autofocus() function are possible with this
application. While it could be customized to work with a known set of
fields (tearing apart the name of the event-processing field and
incrementing the numeral portion to derive the name of the next
field—cc1, cc2, etc.), it
is usually best to generalize the function so that it may be reused
with other field sets on the same page or some other application
later on. Thus, the second argument to autofocus(
) is the number of characters to act as the upper limit of
acceptable length. The same function could be used for the segments
of a U.S. Social Security number, which is in segment lengths of
three, two, and four.

Another possibility that would eliminate the limit
argument is to derive this value from the field's
maxLength property (an integer value). If you
don't need to support Navigator 4 (which lacks this
property), remove the argument from the list and modify the
if condition to the following:

if (charCode > 31 && field.value.length = = field.maxLength) {

The reason for the initial character code analysis is to allow
Shift-Tab to move focus in the reverse direction through these fields
for the user's convenience. If you include the
low-order ASCII characters in the four-character limit, the user
could become lost in a frustrating focus circle.