Open In App

Set the focus to HTML form element using JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

To set focus to an HTML form element, there can be many methods that can be used to focus. In this article, we will discuss them all.

These are the following approaches:

Approach 1: Using focus() method

In this approach, we are going to use the focus() method to focus on the HTML element. We are creating a function in which we select an input and call the focus method on it. This method is set to the onclick function, whenever that button is clicked that onclick function will be invoked and it will focus on to input box.

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

html




<!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:

focuss

Focusing on input element

Approach 2: Using window.onload method

In this appraoch we are focusing on the input field by using window.onload method. we are calling focus method when a window loads to the browser.

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

html




<!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:

focissssss

window.onload focusing method



Last Updated : 28 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads