jQuery - select all text from a textarea

后端 未结 6 2053
情书的邮戳
情书的邮戳 2020-11-27 12:03

How can I make it so when you click inside a textarea, its entire content gets selected?

And eventually when you click again, to deselect it.

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 12:52

    To stop the user from getting annoyed when the whole text gets selected every time they try to move the caret using their mouse, you should do this using the focus event, not the click event. The following will do the job and works around a problem in Chrome that prevents the simplest version (i.e. just calling the textarea's select() method in a focus event handler) from working.

    jsFiddle: http://jsfiddle.net/NM62A/

    Code:

    
    
    
    

    jQuery version:

    $("#foo").focus(function() {
        var $this = $(this);
        $this.select();
    
        // Work around Chrome's little problem
        $this.mouseup(function() {
            // Prevent further mouseup intervention
            $this.unbind("mouseup");
            return false;
        });
    });
    

提交回复
热议问题