[removed] cross browser solution for selecting all text inside a textbox on focus

前端 未结 4 1698
一生所求
一生所求 2021-01-12 19:35

I\'m after the following functionality:

  • user clicks on or tabs into a textbox
  • all text in the textbox is selected, unless the textbox already had focu
4条回答
  •  走了就别回头了
    2021-01-12 19:47

    Just delay it by a millisecond with setTimeout:

    $('input[type="text"]').live('focus', function() {
        var inp = this;
        setTimeout(function() {
            inp.select();
        }, 1);
    });
    

    http://jsfiddle.net/HmQxZ/14/

    What's happening is some other browser event is setting the selection after you've selected the text. So, by waiting a millisecond, you let all the browser events finish, and then select the text. Nothing will undo it now.

提交回复
热议问题