Focus a Textarea or Text Field
This page shows you to make a text field or text area automatically active when the page loads. This means that as soon as the page has loaded the user can begin typing without having to click in the text field first.
- When a text field is active it is said to be focused. Setting the focus means making the field active so the cursor is blinking and ready to accept text input.
- This method can also be used to make a text field active when something else happens (see below).
The following example shows a text field in a form:
<input type="text" name="mytextfield">
Add the following code to the body tag, substituting the form and field names for your own:
That's all there is to it — the OnLoad command instructs the browser to wait until all elements are loaded and then set the focus to the specified form/text field. You're good to go!
Setting Focus From Another Event
You can also cause the focus to be set from another event such as a button click, like this:
The code is very similar. Simply change the command to onClick and add it to the button:
<input type="text" name="mytextfield2">
<input type="button" name="mybutton" value="Set Focus" OnClick="document.myform2.mytextfield2.focus();">
Don't want to use body OnLoad?
In some cases you may not want to (or be able to) place anything in the body tag. In this case you can just insert the code into the page, anywhere after the form (so the form loads first). This example is a variation on the one above: