user9402741
user9402741

Reputation:

On button click focus input in JavaScript

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

Answers (1)

Mamun
Mamun

Reputation: 68943

autofocusis 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

Related Questions