Open In App
Related Articles

Set the focus to HTML form element using JavaScript

Improve Article
Improve
Save Article
Save
Like Article
Like

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example.

Example 1: The focus() method is set to the input tag when user clicks on Focus button.




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Set focus to HTML form element
    </title>
</head>
  
<body>
    <p>
        Click on button to set focus
        on input field
    </p>
      
    <form>
        <input type="text" id="input1">
          
        <br><br>
          
        <button type="button" onclick="focusInput()">
            Set Focus
        </button>
    </form>
      
    <script>
        function focusInput() {
            document.getElementById("input1").focus();
        }
    </script>
</body>
  
</html>                    

Output:

  • Before Clicking the button:
  • After Clicking the button:

Example 2: This example focuses on the input field automatically on page load.




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Set focus to HTML form element
    </title>
</head>
  
<body>
  
    <p>
        Click on button to focus
        on the input field.
    </p>
      
    <form>
        Name: <input type="text" id="input1">
          
        <br><br>
          
        Age: <input type="text" id="input2">
    </form>
      
    <script>
        window.onload = function() {
            document.getElementById("input1").focus();
        }
    </script>
</body>
  
</html>                    

Output:

Example 3: The following program focuses on the input field when clicked on Focus button. To blur the focused input field, the blur() property can be used.




<!DOCTYPE html>
<html>
  
<head>
    <title>
        Set focus to HTML form element
    </title>
</head>
  
<body>
    <p>
        Click on button to focus
        on the input field.
    </p>
      
    <form>
        <input type="text" id="input1">
          
        <br><br>
          
        <button type="button" onclick="focusInput()">
            Focus
        </button>
          
        <button type="button" onclick="blurInput()">
            Blur
        </button>
    </form>
      
    <script>
        function focusInput() {
            document.getElementById("input1").focus();
        }
        function blurInput() {
            document.getElementById("input1").blur();
        }
    </script>
</body>
  
</html>                    

Output:

  • Before Clicking the button:
  • After Clicking on Focus button:
  • After Clicking on Blur button:

Last Updated : 20 May, 2019
Like Article
Save Article
Similar Reads
Related Tutorials