Rayne
Rayne

Reputation: 32675

How can I set the focus to a certain element in a form using JavaScript?

My page has a form that has a text field in it. I'd like to set the focus to that text field as soon as the page loads, so that users do not have to click it to start typing. How can I do this?

Upvotes: 1

Views: 207

Answers (4)

scripter
scripter

Reputation: 130

use autofocus attribute like this:

<html>
<head>

</head>
<body>
<dl>
<dt><label>username:</label><dt>
<dd><input type="text" autofocus></dd>

<dt><label>password:</label><dt>
<dd><input type="password"></dd>

</dl>
</body>

Upvotes: 0

meo
meo

Reputation: 31259

you have to select your element first and then focus it by using focus() :P

function hokusfocus(e)
{
  var fokus = document.getElementById(e);
  fokus.focus();
}

onload = hokusfocus("yourId"); /* makes sure your document is loaded before the focus */

Upvotes: 2

Paul Creasey
Paul Creasey

Reputation: 28874

Did you try googling this?

document.getElementById("textboxId").focus();

Upvotes: 1

Nathan Osman
Nathan Osman

Reputation: 73285

Use the focus() method on the object.

For example:

document.getElementById("something").focus();
...
<input type='text' id='something' />

Upvotes: 3

Related Questions