Open In App

How to select all Text in HTML Text Input when clicked using JavaScript?

Last Updated : 04 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To select the text in HTML Text Input we can use the JavaScript DOM methods and we will select the text when we click the text box.

Using document.getElementById() method

Syntax:

<input onClick="this.select();" >

or

document.getElementById("ID").select();

Example 1: We will use “this.select()” in this example to select the text.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        Select all text in HTML
        text input when clicked
    </title>

</head>

<body>
    <br> Input Text:
    <br>
    <input onClick="this.select();" 
           type="text" value="GeeksforGeeks">
</body>

</html>

Output:

gif

Example 2: We will use DOM Input Text select() Method in this example to select the text. We are going to select the text when we click the try it button.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>
        Select all text in HTML
        text input when clicked
    </title>
</head>

<body>
    Input Text:
    <br>
    <input type="text" value="GeeksforGeeks" id="eid">

    <button type="button" onclick="myFunction()">
        Try it
    </button>

    <script>
        function myFunction() {
            document.getElementById(
                "eid").select();
        }
    </script>

</body>

</html>

Output:

gif




Next Article
Article Tags :

Similar Reads