This post will discuss how to set focus on the input text box in JavaScript and jQuery.

1. Using jQuery

With jQuery, you can use the .focus() method to trigger the “focus” JavaScript event on an element. This method is a shortcut for .trigger("focus") method.

jQuery


HTML



Edit in JSFiddle

 
To set cursor after the last character in the input text box, you can do like:

jQuery


HTML



Edit in JSFiddle

2. Using JavaScript

In JavaScript, you can fire the JavaScript focus event with the .focus() method.

JS


HTML



Edit in JSFiddle

 
To set the cursor at the end of the input text box, you can do like:

JS


HTML



Edit in JSFiddle

3. In HTML

In HTML, you can use the autofocus HTML attribute to set the focus on associated <input> element. However, this sets focus only at the page load time but can’t set focus later programmatically.

That’s all about setting focus to the input text box in JavaScript and jQuery.