AutoTabbing in a form

Jake Howlett, 10 November 2000

Category: Forms; Keywords: tab limit input

This is one of those things that you get used to seeing in standard applications on your PC but very rarely in a browser. It automatically tabs from one input field to the next when it is the required length. A classic example of this is a phone number field, where a 4 digit dialing code is required in the first field, followed by a 6 digit number in the next.

The example below has four fields where the length of the required input in each is 1, 2, 3 and 4 digits, respectively. Try typing in to each one and see what happens:

Limit=1Limit=2Limit=3Limit=4
No limit


The code needed to do this is called from the onKeyUp event of the fields. Like so:

<input name="irrelevant" onKeyUp="return autoTab(this, 3, event);" size="4" maxlength="3">


The function being called is:

var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab( input, len, e ) {
var keyCode = (isNN) ? e.which : e.keyCode;
var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
if( input.value.length >= len && !containsElement( filter, keyCode ) ) {
input.value = input.value.slice( 0, len );
input.form[ (getIndex( input ) + 1 ) % input.form.length ].focus();
}


And this, in turn, requires the following functions:

function containsElement(arr, ele) {
var found = false, index = 0;
while(!found && index < arr.length)
if(arr[index] == ele)
found = true;
else
index++;
return found;
}

function getIndex(input) {
var index = -1, i = 0, found = false;
while (i < input.form.length && index == -1)
if (input.form[i] == input)index = i;
else i++;
return index;
}
return true;
}


How does it work? Well every time a key is pressed in any of these fields it calls the autoTab function. This checks whether the current length of the field is within its limits. If not then it is "clipped" and focus is given to the next field on the form. Checks are also made as to the Unicode character of the key that is pressed to verify it was not simply a key such as shift or ctrl or whatever.