I am trying to autofocus
input on button click but it doesn't work. Code can be found here for edit: https://www.w3schools.com/code/tryit.asp?filename=FPPCFP5RTU9E
<input type="text" id="myText" autofocus>
<button onclick="myFunction()">Focus Input</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("myText").autofocus = true;
}
</script>
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.
JavaScript | Focus() JavaScript focus method is used to give focus to a html element. It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc.
autofocus is an HTML attribute. If you want to set the focus property by JavaScript you have to use focus (). Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. Provide details and share your research! But avoid … Asking for help, clarification, or responding to other answers.
on the input field. Example 3: The following program focuses on the input field when clicked on Focus button. To blur the focused input field, the blur () property can be used.
autofocus
is an HTML attribute. If you want to set the focus property by JavaScript you have to use focus()
.
So try document.getElementById("myText").focus();
:
Working Code:
function myFunction() {
document.getElementById("myText").focus();
}
<input type="text" id="myText" autofocus>
<button onclick="myFunction()">Focus Input</button>
<p id="demo"></p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With