Open In App

How to set the focus to the first form field ?

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we’ll discuss how to set focus on the first form field. By setting the focus on the first form field, we indicate the user from where to begin. It increases the readability of a form in a webpage. There are various approaches to do so, we’ll explain two of them with suitable examples.

Approach 1: Using HTML <input> autofocus attribute. Autofocus is a boolean attribute, used along with an <input> element in a form. The form field is focused on automatically when the page loads.

Example 1: In this example, we will see the use of HTML <input> autofocus attribute.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Set focus to the first form field</title>
</head>
  
<body>
    <h1>
        <center>Welcome to GFG</center>
    </h1>
    <center>
        <form>
            Email id: <input type="text" id="input1" 
                autofocus />
            <br /><br />
  
            Password: <input type="text" id="input2" />
            <br /><br />
              
            <button type="submit">Submit</button>
        </form>
    </center>
</body>
  
</html>


Output: 

Approach 2: Using focus() method in JavaScript. The focus() method can be used to set both automatic and manual focus to the specified form field. You can read more about this method here.

Example 2: In this example, we will see the use of the focus() method.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Set focus to the first form field</title>
</head>
  
<body>
    <h1>
        <center>Welcome to GFG</center>
    </h1>
    <center>
        <form>
            Email id: <input type="text" id="input1" /> 
            <br /><br />
              
            Password: <input type="text" id="input2" />
            <br /><br />
              
            <button type="submit">Submit</button>
        </form>
    </center>
      
    <script>
        window.onload = function () {
            document.getElementById("input1").focus();
        };
    </script>
</body>
  
</html>


Output: 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads