How to Select All HTML Textarea Text on Click Using JavaScript?

Selecting all textarea text using JavaScript

You can select all text in an HTML <textarea> element in the following ways:

Select All Textarea Text When It's Clicked On

To select all text in an HTML <textarea> element when it's clicked on, you can use the HTMLTextAreaElement.select() method, for example, in the following way:

<textarea onclick="this.select()">Hello world!</textarea>

Alternatively, you may use the HTMLTextAreaElement.setSelectionRange() method to achieve the same:

<textarea
    onclick="this.setSelectionRange(0, this.value.length)"
>
    Hello world!
</textarea>

If you do not wish to inline JavaScript, you may create an event handler function for the click event, for example, like so:

const textarea = document.getElementById('foo');

textarea.addEventListener('click', function (e) {
    e.target.select();
});

Or, alternatively, you can do the same using HTMLTextAreaElement.setSelectionRange(), for example, like so:

const textarea = document.getElementById('foo');

textarea.addEventListener('click', function (e) {
    const target = e.target;
    target.setSelectionRange(0, target.value.length);
});

You will have to replace "foo" with the value you assign to the id attribute of the <textarea> element.

Select All Textarea Text When a Button is Clicked

Consider you have the following <textarea> and a "select all" <button> element:

<textarea id="foo">Hello world!</textarea>
<button onclick="selectAllText('foo')">Select All</button>

You could implement the "selectAllText()" function (which is called when the button is clicked) as follows:

function selectAllText(id) {
    const textarea = document.getElementById(id);
    textarea.focus();
    textarea.select();
}

Or, alternatively, you could use HTMLTextAreaElement.setSelectionRange() to achieve the same:

function selectAllText(id) {
    const textarea = document.getElementById(id);
    textarea.focus();
    textarea.setSelectionRange(0, textarea.value.length);
}

Calling HTMLElement.focus() is important as just using HTMLTextAreaElement.select() (or HTMLTextAreaElement.setSelectionRange()) will not necessarily focus the textarea.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.