skip to Main Content

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.

Notes:

  • 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:

<form name="myform">
<input type="text" name="mytextfield">
</form>

Add the following code to the body tag, substituting the form and field names for your own:

<body OnLoad=”document.myform.mytextfield.focus();”>

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!

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:

<script type=”text/javascript” language=”JavaScript”>
document.forms[‘myform’].elements[‘mytextfield’].focus();
</script>

Alphonse

Editorial Staff at ETN Multimedia is led by Alphonse Tan. Page maintained by Alphonse Tan

Back To Top