How to select all text in HTML text input when clicked using JavaScript?

By IncludeHelp Last updated : November 15, 2023

To select all text in HTML text input when clicked using JavaScript, either use the this.select() or document.getElementById("ID").select() method. Use these methods on the click event.

Methods to select all text in HTML text input when clicked

  1. Using this.select() method
  2. Using DOM Input Text .select() method

Using this.select() method

Call this.select() method onClick event of the Input text.

Example

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Document title</title>
  </head>
  
  <body>
    <h1>DEMO: Select all text in HTML text input when clicked using JavaScript</h1>
    <input type="text" id="txtInput" onClick="this.select();" value="Hello world!"/>
  </body>
</html>

The output of the above example is:

select all text in HTML text input when clicked (1)

Using DOM Input Text .select() method

Give an ID to the input text, and write a JavaScript method containing the DOM event and then call this method on the onClick event of the button.

Example

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Document title</title>
  </head>
  
  <body>
    <h1>DEMO: Select all text in HTML text input when clicked using JavaScript</h1>
    <input type="text" id="txtInput" value="Hello world!"/>
    <button id="btnClick" onClick="setFocusToInputBox();">Set Focus!</button>
  </body>
  
  <script type="text/javascript">
    function setFocusToInputBox(){
    	document.getElementById("txtInput").select();
    }
  </script>
</html>

The output of the above example is:

select all text in HTML text input when clicked (2)

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.