Select the text in the input field, but editing is disabled

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 in order:

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

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

return false;

});

But I also want to disable editing. If I believe false; to the keydown event, ctrl + c does not work. If I disabled = "disabled" at the input, the selection does not work.

Any idea? Thanks.

+6
jquery input select
source share
3 answers

You want to add the readonly attribute instead of the disabled attribute:

 <input type="text" name="" readonly="readonly" value="http://google.com" /> 
+14
source share

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

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

Check out the working example http://jsfiddle.net/hAVg9/

+1
source share

A read-only assignment is very different from a disconnected one, and their location is very different.

To select or even copy text from disabled input, you can follow the Andy E suggestion

Or, as in my case, so that the button (input group-attached) is associated with the input text. And then at the click of a button:

  1. enable text input
  2. choose or focus or what do you want to do
  3. disconnect again

Like this:

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

Full example no jsfiddle

0
source share

All Articles