Set Focus to an HTML Form Element Using JavaScript

Last Updated : 10 Sep, 2026

Setting focus to an HTML form element using JavaScript allows users to immediately interact with a specific input field. This can improve user experience, especially when filling out forms.

JavaScript provides different ways to set focus on an element. The focus() method is commonly used either in response to a user action or automatically when the webpage loads.

Approach 1: Using focus() Method

The focus() method sets focus on a specified HTML element. In this approach, the input element is selected using getElementById(), and the focus() method is called when the user clicks a button.

Syntax:

element.focus();

Example: This example sets focus on the input field when the user clicks the Set Focus button.

html
<!DOCTYPE html>
<html>

<head>
    <title>Set Focus to HTML Form Element</title>
</head>

<body>

    <p>
        Click the button to set focus
        on the input field.
    </p>

    <form>
        <input type="text" id="input1"
               placeholder="Enter your name">

        <br><br>

        <button type="button" onclick="focusInput()">
            Set Focus
        </button>
    </form>

    <script>
        function focusInput() {
            document.getElementById("input1").focus();
        }
    </script>

</body>

</html>

Output:

focuss
Focusing on input element

Approach 2: Using window.onload Method

In this approach, the window.onload event is used to set focus automatically when the webpage finishes loading. The focus() method is called inside the window.onload function.

Syntax:

window.onload = function () {
element.focus();
};

Example: This example automatically sets focus on the input field when the webpage loads.

html
<!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>
        <label for="name">Name:</label>
        <input type="text" id="name">

        <br><br>

        <label for="age">Age:</label>
        <input type="text" id="age">
    </form>

    <script>
        window.onload = function () {
            document.getElementById("name").focus();
        };
    </script>

</body>

</html>

Output:

focissssss
window.onload focusing method
Comment