13

I've got a textbox (set to readonly) and I need its' contents to be selected for easy copy/paste when it gains focus. Using the code below it only seems to quickly select the text and then unselect it for some reason.

HTML

<input id='thing' type='text' value='some text' readonly='readonly' />​

JavaScript

document.getElementById('thing').onfocus = function(){
    this.select();
};​

Fiddle: http://jsfiddle.net/cfqje/

Ross
  • 995
  • 15
  • 32
FiniteLooper
  • 24,161
  • 22
  • 88
  • 126

2 Answers2

20

This seems to be a work around:

<input id='thing' type='text' value='some text' onclick="this.select()" readonly='readonly' />​

I guess the problem is that focus doesn't work correctly as the input is readonly.

fuxia
  • 61,802
  • 6
  • 50
  • 60
JNK
  • 1,713
  • 8
  • 25
  • 37
0

You can now use CSS. With user-select: all; all text will be selected when a clicking on an element.

Frank Lämmer
  • 1,952
  • 18
  • 23
  • I like this a lot, just be aware that the _"all"_ option might be buggy in Safari, according to [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/user-select#Syntax). – jhaskell Jan 10 '17 at 02:34
  • 2
    does not work with `readonly` elments (just tested in Chrome 86) – Alex from Jitbit Nov 10 '20 at 16:04