11

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>

1 Answer 1

36

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.