John Mwaniki /   29 Jul 2023

How to set focus on an HTML form input using jQuery

When working with HTML forms, the term "focus" refers to the state of an input element or form control when it is currently selected or activated by the user.

When an input element is in focus, it means that the user can interact with it directly, such as typing text into a text field or selecting an option from a dropdown menu.

The focus state is visually indicated by most web browsers by adding a focus outline around the focused element. This makes the input field distinct and stands out from the rest of the content.

The color of the outline may differ from one browser to another but can be standardized using the CSS :focus pseudo-class as below:

input:focus {
  background: #f7e7b9;
  outline: 2px solid green;
}

Click on any of the form inputs below and you will see the custom outline and background color on focus as set above.

The focus state is typically triggered by:

  • Clicking: When a user clicks on an input element, it gains focus, allowing them to interact with it.
  • Tabbing: Users can navigate through form elements using the "Tab" key on their keyboard. As they cycle through the form controls, each element in the tab order gains focus.
  • Use of autofocus Attribute: The autofocus attribute in an HTML input element specifies that the element should automatically get focused when the page loads.
    <input type="text" id="name" autofocus placeholder="Enter your name">
  • Programmatic Focus: It's also possible to set focus on an input element programmatically using JavaScript. For instance, when a user loads a page, you can automatically set focus on a specific input field.

Setting focus to an input field using jQuery

We can set focus on a specific HTML form element programmatically in jQuery on page load or when the user triggers a specific event such as a click.

The focus() method is used to set focus on any element that can be focused.

Syntax

$("selector").focus()

The "selector" above refers to what is used to target the element such as the tag name, element ID, or its class name.

Example 1

$(function() {
  $("#name").focus();
});

The above jQuery code sets the focus to a form element with the ID "name" when the page loads.

Example 2

$(function() {
  $(".mybtn").click(function(){
    $("#email").focus();
  });
});

The code above sets the focus to an HTML form element with the ID "email" when a button with class "mybtn" is clicked as shown below:

That's all!

Now you know how to programmatically set focus to HTML form elements using jQuery.