devxlogo

Bringing focus to a form element upon loading

Bringing focus to a form element upon loading

Question:
Is it possible to bring focus to a particular form element, such as the first text area of a form, when the document loads? It must be, but for the forms I encounter, the focus is controlled manually by the user. I find this inconvenient! Focus should be automatic, leaving the user with only the task of tabbing between form elements.

Answer:
Most form elements (text boxes, radio buttons, etc.) have a method called focus, which can be used just for this purpose. Simply add an onLoad event to your document’s tag so that the focus method is called when the form is loaded.

Example

The following source describes a log-in form that automatically places keyboard focus in the username field:

onLoad="document . loginform . username . focus ();">Please identify yourself:
username: password:

When the form is completely loaded, the tag’s onLoad event will fire, which will give keyboard focus to the form’s username element.

devx-admin

Share the Post: