Deselect contents of a textbox with javascript

后端 未结 8 1358
醉话见心
醉话见心 2020-12-10 13:47

I understand that with javascript you can select the contents of a textbox with the following code (in jQuery):

$(\"#txt1\").select();

Is t

8条回答
  •  囚心锁ツ
    2020-12-10 14:02

    You need to set the selectionStart and selectionEnd attribute. But for some reason, setting these on focus event doesn't work (I have no idea why). To make it work, set the attributes after a small interval.

      $(document).ready(function(){
        $('#txt1').focus(function(){
          setTimeout(function(){
            // set selection start, end to 0
            $('#txt1').attr('selectionStart',0);
            $('#txt1').attr('selectionEnd',0);
          },50);  // call the function after 50ms
        });
      });
    

提交回复
热议问题