Select the text in the input field, but the editin

2019-06-19 01:37发布

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.

3条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-19 02:02

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/

查看更多
虎瘦雄心在
3楼-- · 2019-06-19 02:17

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

查看更多
混吃等死
4楼-- · 2019-06-19 02:22

You want to add the readonly attribute instead of disabled:

<input type="text" name="" readonly="readonly" value="http://google.com" />
查看更多
登录 后发表回答