Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to set the focus to the first form field ?

  • Last Updated : 27 Aug, 2021

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:

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:

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: 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!