Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 956
Gragas Incoming Avatar asked Mar 25 '18 12:03

Gragas Incoming


People also ask

How to set focus on input text box in JavaScript and 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.

What is the use of focus in JavaScript?

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.

How do I set autofocus in JavaScript?

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.

How to blur the focused input field in JavaScript?

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.


1 Answers

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>
like image 112
Mamun Avatar answered Sep 20 '22 15:09

Mamun