Set focus to input text box with JavaScript/jQuery
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
|
1 2 3 4 5 |
$(document).ready(function() { $('#submit').click(function() { $("#name").focus(); }) }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Name:</label> <input type="text" id="name"> </div> <button id="submit">Focus</button> |
To set cursor after the last character in the input text box, you can do like:
jQuery
|
1 2 3 4 5 6 |
$(document).ready(function() { $('#submit').click(function() { var value = $("#name").val(); $("#name").focus().val('').val(value); }) }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Name:</label> <input type="text" id="name"> </div> <button id="submit">Focus</button> |
2. Using JavaScript
In JavaScript, you can fire the JavaScript focus event with the .focus() method.
JS
|
1 2 3 |
document.getElementById("submit").onclick = function() { document.getElementById("name").focus(); } |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Name:</label> <input type="text" id="name"> </div> <button id="submit">Focus</button> |
To set the cursor at the end of the input text box, you can do like:
JS
|
1 2 3 4 5 6 7 8 |
document.getElementById("submit").onclick = function() { var input = document.getElementById("name"); input.focus(); var val = input.value; input.value = ''; input.value = val; } |
HTML
|
1 2 3 4 5 |
<div id="container"> <label for="name">Name:</label> <input type="text" id="name"> </div> <button id="submit">Focus</button> |
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.
|
1 2 3 4 5 |
<div id="container"> <label for="name">Name:</label> <input type="text" id="name" autofocus> </div> <button id="submit">Focus</button> |
That’s all about setting focus to the input text box in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)