Categories
HTML Tutorials

Automatically focusing on an input element

You can select which input element the browser focuses on when the form is displayed. This means the user can start typing directly into the selected field without having to explicitly select it first. You specify which input element the focus should be applied to with the autofocus attribute.

Using the autofocus attribute
<html>
  <head>
    <title>Example</title>
    <meta name="author" content="Adam Freeman"/>
    <meta name="description" content="A simple example"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  </head>
  <body>
    <form method="post" action="http://titan:8080/form">
      <p>
        <label for="fave">Fruit: <input autofocus id="fave" name="fave"/></label>
      </p>
      <p>
        <label for="name">
          Name: <input id="name" name="name"/>
        </label>
      </p>
      <button>Submit Vote</button>
    </form>
  </body>
</html>

As soon as the browser displays the page, it will focus on the first input element. You can see the visual cue Google Chrome gives to the user to indicate a focused element below.

You can apply the autofocus attribute only to one input element. If you try to apply the element more than once, the browser will focus on the last element in the document that has the element.