Select all text on focus using jQuery

后端 未结 3 866
谎友^
谎友^ 2021-01-07 19:52

I have a little jQuery function that is meant to automatically select text in an asp.net text box when it gets focus. However, the text in the text box gets selected, but im

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-07 20:17

    I had a similar problem with a product search form I was working on. I know that this has already been answered, but I figured it can't hurt to submit my code, right?

    $('#product-search').focus(function(){
        $('#product-search').mouseup(function(){
            $(this).select(function(){
                $(this).off('mouseup');
            });
    
            $(this).select();
        });
    });
    

    The advantage being that it only selects the text when the form first gets focus, rather than every time the form gets clicked, such as when a user wants to select a portion of the text.

    I rewrote Marcel's fiddle to demonstrate the difference. http://jsfiddle.net/7tDYq/2/

提交回复
热议问题