Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I can't work out why I can't get the the content of a textarea to be selected when the textarea receives focus.

Please visit a live example here: http://jsfiddle.net/mikkelbreum/aSvst/1

Using jQuery, this is my code. (IN SAFARI) It makes the text selected in case of the click event, but not the focus event:

$('textarea.automarkup')
.mouseup(function(e){
    // fixes safari/chrome problem
    e.preventDefault();
})
.focus(function(e){
    $(this).select();
})
.click(function(e){
    $(this).select();
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
472 views
Welcome To Ask or Share your Answers For Others

1 Answer

The simplest thing to do is to combine your existing code with a timer, since the focus event is generally too early in WebKit:

jsFiddle example: http://jsfiddle.net/NWaav/2/

Code:

$('textarea.automarkup').focus(function() {
    var $this = $(this);

    $this.select();

    window.setTimeout(function() {
        $this.select();
    }, 1);

    // Work around WebKit's little problem
    function mouseUpHandler() {
        // Prevent further mouseup intervention
        $this.off("mouseup", mouseUpHandler);
        return false;
    }

    $this.mouseup(mouseUpHandler);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...