简体   繁体   中英

Select all text in a 'readonly' <input /> when it gains focus

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/

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM