JavaScript EditorFree JavaScript Editor     DHTML Editor 

Main Page Previous Section Next Section

8.7 Advancing Text Field Focus with the Enter Key

NN 4, IE 4

8.7.1 Problem

You want to use the Enter/Return key in a text field to give focus to the next text field in the form.

8.7.2 Solution

Include an onkeypress event handler in each field that needs to advance focus to another field in the form. The event handler should invoke the focusNext( ) function described in the Discussion. The event handler must pass arguments for the form reference, the name of the next field in sequence, and (for the W3C event model in NN) the event object. For example, the event handler in a field called name1 directs focus to field name2 in the following:

<input type="text" name="name1" id="name1" 
    onkeypress="return focusNext(this.form, 'name2', event)">

8.7.3 Discussion

Although HTML forms don't normally follow the user interface behavior of standalone database form programs, you can script text input fields to advance focus to the next field when the user presses the Enter/Return key. The scripting task is a bit tedious because each event handler must be tailored to focus a specific field that is next in the sequence. First, block all submissions using onsubmit="return false" in the <form> tag. The following function is invoked from each text field:

function focusNext(form, elemName, evt) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode :
        ((evt.which) ? evt.which : evt.keyCode);
    if (charCode =  = 13 || charCode =  = 3) {
        form.elements[elemName].focus( );
        return false;
    return true;

Continue to use the onchange event handlers in the text boxes to perform real-time validations as well as the auto-focusing via onkeypress.

8.7.4 See Also

Recipe 8.12 for automatically advancing focus to an adjacent text box in fixed-length fields.

    Main Page Previous Section Next Section

    JavaScript EditorJavaScript Checker     DHTML Editor