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

前端 未结 4 1699
一生所求
一生所求 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:39

    If you can use jQuery then you can do something like;

    $("#myInputField").focus(function(){
        // Select input field contents
        this.select();
    });
    
    // Add this behavior to all text fields
    $("input[type=text]").focus(function(){
        // Select field contents
        this.select();
    });
    

    Taken from HERE

    0 讨论(0)
  • 2021-01-12 19:40

    You should remember to do a return false; event.stopPropagation(); event.preventDefault() like so:

    $('input[type="text"]').live('click', function (event) {
        this.select();
        event.stopPropagation();
        event.preventDefault();
        return false;
    });
    

    http://jsfiddle.net/7rYLV/

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-12 19:53

    You may want to add

    event.preventDefault();
    return false;
    

    to your function (the first one). That may fix the other browsers.

    Also, add event to the function sig:

    $('input[type="text"]').live('focus', function (event) {
    
    0 讨论(0)
提交回复
热议问题