Open In App

JQuery | Set focus on a form input text field on page load

Last Updated : 25 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The task is to set the focus on form input text field using jQuery. To do so, Here are a few of the most used techniques discussed. First focus() method needs to be discussed.

jQuery focus() Method

The focus event happens when an element gets focus (Either selected by a mouse click or by “tab-navigating” to it). This method triggers the focus event or adds a function to run when the focus event occurs.

Syntax:

  • Trigger the focus event for selected elements:
    $(selector).focus()
  • Attach a function to the focus event:
    $(selector).focus(function)

Parameters:

  • function: This parameter is optional. It specifies the function to execute when the focus event occurs.

Example 1: In this example the form input text field gets the focus as page loads by using focus() method. Here the input element is selected by input keyword in jQuery selector.

html




<!DOCTYPE HTML>
<html>
 
<head>
    <title>
        How to Set focus on a form input text
        field on page load using jQuery?
    </title>
 
    <script src=
    </script>
</head>
 
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <h4>
        This input box gets focused
        as the page loads
    </h4>
 
    <form id="form">
        Input :
        <input type="text" name="input_field" />
    </form>
 
    <script>
        $("input:text").focus();
    </script>
</body>
 
</html>


Output:

focused-input

Example 2: In this example the form input text field gets the focus as page loads by using focus() method. Here the input element is selected by id of form element and its own id in jQuery selector.

html




<!DOCTYPE HTML>
<html>
 
<head>
    <title>
        How to Set focus on a form input text
        field on page load using jQuery?
    </title>
 
    <script src=
    </script>
</head>
 
<body style="text-align:center;">
 
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <h4>
        This input box gets focused
          as the page loads
    </h4>
 
    <form id="form">
        Input :
        <input id="form_input" type="text"
            name="input_field" />
    </form>
 
    <script>
        $("#form #form_input").focus();
    </script>
</body>
 
</html>


Output:

focused-input



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads