How to Set Default HTML Form Focus Without Javascript

Solutions with HTML

It is possible to set a default input focus on an HTML form without Javascript. This can be done in HTML5, as it allows us to use the autofocus attribute on the form element.

Example of setting a default form focus:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <input type="text" name="myInput" autofocus />
  </body>
</html>

Result

In the example above, we used one <input> element and added the autofocus attribute to it.

Let’s see another example, where we use a few <input> elements, and set the autofocus attribute only on one of them.

Example of setting focus only for one <input> element:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document.</title>
    <style>
      div {
        margin-bottom: 10px;
      }
      label {
        display: inline-block;
        width: 70px;
      }
    </style>
    <body>
      <h1>Example</h1>
      <form action="/form/submit" method="get">
        <div>
          <label for="name">Name:</label>
          <input type="text" id="name" name="name" autofocus>
        </div>
        <div>
          <label for="surname">Surname:</label>
          <input type="text" id="surname" name="surname">
        </div>
        <div>
          <label for="year">Year:</label>
          <input type="number" id="year" name="year" value="2020" disabled>
        </div>
        <input type="submit">
      </form>
    </body>
</html>

For the first <input>, we set the autofocus attribute, and for the third <input>, we set the disabled attribute. Here, we also used some CSS and set the margin-bottom property for the <div> element, and specified the display property with the “inline-block” value and width property for the <label> element.