I want to select all of the text inside of a textarea when a user clicks the textarea. I tried onclick="this.focus()"
, but this didn't do anything. I tried onclick="this.highlight()"
, but this caused an error. What should I do?
The select() method selects the entire contents of a text area.
You can't actually highlight text in a <textarea> . Any markup you would add to do so would simply display as plain text within the <textarea> . The good news is, with some carefully crafted CSS and JavaScript, you can fake it.
Highlight using the HTML5 <mark> tag If you are working on an HTML5 page, the <mark> tag can quickly highlight text. Below is an example of the how to use the mark tag and its result. If your browser supports the <mark> tag, "highlighted text" should have a yellow background.
This may annoy your users since it prevents the useful default behaviour of placing the caret where the user clicked and I therefore recommend against it in general. That said, the solution for most browsers is onclick="this.select()"
.
However, this will not work in Chrome [UPDATE February 2014: it does now seem to work in recent versions of Chrome]. For a workaround and general background on this issue, see the following question: jQuery - select all text from a textarea
onclick="this.focus();this.select()" readonly="readonly"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With