JavaScript EditorFree JavaScript Editor     DHTML Editor 

Main Page Previous Section Next Section

8.1 Auto-Focusing the First Text Field

NN 2, IE 3

8.1.1 Problem

You want the user to begin typing into the first text box of a form without having to physically bring focus to the box.

8.1.2 Solution

Assuming that the page always contains a form and text field with the same names, use an onload event handler to invoke the focus( ) method of the text box:

<body onload="document.formName.fieldName.focus( )">

Substitute the name of your form and text box for the two placeholders in this code.

8.1.3 Discussion

As simple as this solution is, you'll be amazed how much it helps casual users get faster results from a page's form. The Google search form uses a similar technique so that all a user needs to do is select the site from the Favorites/Bookmarks list and start typing the query string. Without this scripted assistance, users of most browsers have to click on the text box or press the Tab key a couple of times to bring focus to the text box. You must wait for the page to complete its loading process before giving the text box focus, or some browsers will grab focus away from the box.

If you deliver the text box with default or sample text that is to be replaced by the user, you should also invoke the select( ) method of the box:

<body onload=
   "document.formName.fieldName.focus( ); ) ">

This action also selects the text in the box, such that the next keyboard key that gets pressed removes the default text.

8.1.4 See Also

Recipe 8.4 for auto-selecting a form field that fails validation; Recipe 8.10 for auto-tabbing between text boxes with fixed-length entries.

    Main Page Previous Section Next Section

    JavaScript EditorJavaScript Checker     DHTML Editor