6

I have a simple txt input field:

<input type="text" name="" value="http://google.com" />

If i click inside the input, i want to select the text. This part is fine with this:

$('input.highlight').click(function(){

$(this).focus().select();

return false;

});

But, i want to disable the editing also. If i put a return false; to the keydown event, the ctrl+c is not working. If i put disabled="disabled" to the input, the select is not working.

Any idea? Thanks.

Community
  • 1
  • 1
passatgt
  • 4,234
  • 4
  • 40
  • 54

3 Answers3

15

You want to add the readonly attribute instead of disabled:

<input type="text" name="" readonly="readonly" value="http://google.com" />
scunliffe
  • 62,582
  • 25
  • 126
  • 161
  • 1
    Which exact version of Chrome? This is very basic HTML (quite possibly since the HTML Input element was created) - if this fails in a nightly this might be a regression bug. – scunliffe Dec 29 '15 at 05:49
1

With jQuery you can use the keypress() and preventDefault() functions

$('input').click(function(e) {
    $(this).focus().select();
    $(this).keypress(function(e){
    e.preventDefault();
    })

});

Check working example at http://jsfiddle.net/hAVg9/

Hussein
  • 42,480
  • 25
  • 113
  • 143
0

Readonly purpose is very different than disabled, and also theirs layout is very different.

To select or even copy text from an disabled input text, one can follow Andy E suggestion

Or, as my case, to have a button (input-group-appended) associated to the input text. And then on button click:

  1. enable input text
  2. select or focus or what ever you want to do
  3. disable again

Like this:

$('#btnCopy').click(function(){
    $('#txtInputDisabled').removeAttr('disabled');  
    $('#txtInputDisabled').select();
    document.execCommand("copy");
    $('#txtInputDisabled').attr('disabled','disabled');  
});

Complete example no jsfiddle

dchang
  • 1,101
  • 10
  • 13