Automatically Jumping To The Next Field

If your form contains data that is of a fixed length it may be convenient to have the cursor automatically jump to the next field when the proper amount of data is filled in. For example, a social security number consists of three fields of 3, 2, and 4 characters long. We can set those three fields so that the cursor jumps automatically from one to the next as the data is filled in.

First, copy this script exactly as-is into the <HEAD> section of your document.

<SCRIPT TYPE="text/javascript">
<!--
var downStrokeField;
function autojump(fieldName,nextFieldName,fakeMaxLength)
{
var myForm=document.forms[document.forms.length - 1];
var myField=myForm.elements[fieldName];
myField.nextField=myForm.elements[nextFieldName];
if (myField.maxLength == null)
myField.maxLength=fakeMaxLength;
myField.onkeydown=autojump_keyDown;
myField.onkeyup=autojump_keyUp;
}
function autojump_keyDown()
{
this.beforeLength=this.value.length;
downStrokeField=this;
}
function autojump_keyUp()
{
if (
(this == downStrokeField) && 
(this.value.length > this.beforeLength) && 
(this.value.length >= this.maxLength)
)
this.nextField.focus();
downStrokeField=null;
}
//-->
</SCRIPT>

Now, suppose we have this form in which the first three fields represent the social security number. We create the fields as usual without any special markup.

<FORM ACTION="../cgi-bin/mycgi.pl" METHOD=POST>
SSN: 
<INPUT TYPE=TEXT NAME="ssn_1" MAXLENGTH=3 SIZE=3> -
<INPUT TYPE=TEXT NAME="ssn_2" MAXLENGTH=2 SIZE=2> -
<INPUT TYPE=TEXT NAME="ssn_3" MAXLENGTH=4 SIZE=4><BR>
email: <INPUT TYPE=TEXT NAME="email"><BR>
</FORM>

To set the three fields as automatics jumpers, we add a short script immediately after closing the form. The script must come immediately after the form before any other forms. We use the autojump() command once for each field which must auto-jump. autojump() takes three argument: the name of the field which should auto-jump, the name of the field to jump to, and how many characters fills up the field. So these commands set ssn_1 to jump to ssn_2 after three characters, ssn_2 to jump to ssn_3 after two characters, and ssn_3 to jump to email after four characters.

<SCRIPT TYPE="text/javascript">
<!--
autojump('ssn_1', 'ssn_2', 3);
autojump('ssn_2', 'ssn_3', 2);
autojump('ssn_3', 'email', 4);
//-->
</SCRIPT>

This gives us this form:

SSN: - -
email:




About the Author
Copyright 1997-2002 Idocs Inc. Content in this guide is offered freely to the public under the terms of the Open Content License and the Open Publication License. Contents may be redistributed or republished freely under these terms so long as credit to the original creator and contributors is maintained.