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
  • 1,013
  • 14
  • 32
Chris Barr
  • 29,851
  • 23
  • 95
  • 135
  • 4
    Duplicate? http://stackoverflow.com/questions/4067469/selecting-all-text-in-html-text-input-when-clicked – elclanrs Dec 14 '12 at 23:04
  • The Fiddle works for me in Firefox. IE8 as well. What browser is not working for you? – Mike Christensen Dec 14 '12 at 23:07
  • @John Yep, my bad. I guess i forgot to accept this one. I have now. – Chris Barr Mar 19 '15 at 20:27
  • @MikeChristensen the fiddle does not work for me on Chrome 45 – mc9 Sep 18 '15 at 00:27
  • Hmm, strange, yes it no longer works for me in Chrome 45 either. Changing it to an `onclick` event does work for mouse clicks, but this means it will no longer work when the field is focused via keyboard navigation :/ – Chris Barr Sep 18 '15 at 12:04

2 Answers2

21

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
  • 62,923
  • 6
  • 54
  • 62
JNK
  • 1,753
  • 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
  • 2,165
  • 19
  • 26
  • 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