8.4 Auto-Focusing an Invalid Text Field Entry

NN 2, IE 3

8.4.1 Problem

You want to bring focus to an errant or missing text field entry and select all text in the text field for quick replacement.

8.4.2 Solution

The basic solution is to invoke the focus( ) and select( ) methods of the text box under inspection. An unfortunate timing bug (primarily affecting IE for Windows) prevents these calls from occurring immediately in the validation function. An arbitrary time-out is needed to let the failed validation alert window disappear and the rest of the page to settle down before focusing and selecting the text box.

Here's a generic function that can handle any field:

function focusElement(formName, elemName) {
    var elem = document.forms[formName].elements[elemName];
    elem.focus( );
    elem.select( );

Next, modify each text field validation routine so that immediately after the error-reporting alert dialogbut before the return false statementyou invoke the above function through a setTimeout( ) call. Here is the regular expression version of the email address validation function (from Recipe 8.2) with the modification installed and highlighted in bold:

function isEMailAddr(elem) {
    var str = elem.value;
    var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (!str.match(re)) {
        alert("Verify the email address format.");
        setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
        return false;
    } else {
        return true;

Because the first parameter of the setTimeout( ) function is a string, you can pass the necessary information about the form and input elements by way of their string names.

8.4.3 Discussion

You can also invoke the focus( ) (but not the select( )) method on other types of input elements, such as radio buttons and selects, but you'll have to make sure you are invoking the method on the correct element. In the case of a radio button group, the name attribute is the same for all related buttons. You can give focus to only one radio button, so you will need to reference one of the radio buttons of the group by array index (or via unique ID if your scripts have that information).

To differentiate among the different form control types, you can use the type property. For input elements, the type property can return any of the following: button, checkbox, file, hidden, image, password, radio, reset, submit, or text (older browsers do not treat the image type as a scriptable object). A select element can return select-multiple or select-one. Therefore, you can branch a function such as focusElement( ) to invoke the focus( ) method only on those element types that don't provide text input.

8.4.4 See Also

Recipe 8.2 for validation functions that can be adapted to the auto-focus technique; Recipe 8.3 for batch validation techniques that automatically employ the focusing embedded in the individual validation functions.