Home : Internet : JavaScript : Focus

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:

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 >

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:

<form name="myform2">
<input type="text" name="mytextfield2">
<input type="button" name="mybutton" value="Set Focus" ></form>


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>