Reputation:
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>
Upvotes: 11
Views: 68385
Reputation: 68943
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>
Upvotes: 36