Selecting text on focus using jQuery not working in Safari and Chrome

前端 未结 9 1747
耶瑟儿~
耶瑟儿~ 2020-11-28 20:45

I have the following jQuery code (similar to this question) that works in Firefox and IE, but fails (no errors, just doesn\'t work) in Chrome and Safari. Any ideas for a wo

相关标签:
9条回答
  • 2020-11-28 21:31

    Because there is flickering when you use setTimeout, there is another event based solution. This way the 'focus' event attach the 'mouseup' event and the event handler detach itself again.

        function selectAllOnFocus(e) {
        if (e.type == "mouseup") { // Prevent default and detach the handler
            console.debug("Mouse is up. Preventing default.");
            e.preventDefault();
            $(e.target).off('mouseup', selectAllOnFocus);
            return;
        }
        $(e.target).select();
        console.debug("Selecting all text");
        $(e.target).on('mouseup', selectAllOnFocus);
    }
    

    Then wire the first event

        $('.varquantity').on('focus', selectAllOnFocus);
    
    0 讨论(0)
  • 2020-11-28 21:37

    While this works for selecting it in IE, Firefox, Chrome, Safari, and Opera, it won't let you edit it by clicking a second time in Firefox, Chrome, and Safari. Not entirely sure, but I think this may be due to those 3 browsers re-issuing a focus event even though the field already has focus thus never allowing you to actually insert the cursor (since you're selecting it again), whereas in IE and Opera it appears it isn't doing that so the focus event didn't get fired again and thus the cursor gets inserted.

    I found a better fix in this Stack post that doesn't have that problem and works in all browsers.

    0 讨论(0)
  • 2020-11-28 21:45

    It's the onmouseup event that is causing the selection to get unselected, so you just need to add:

    $("#souper_fancy").mouseup(function(e){
        e.preventDefault();
    });
    
    0 讨论(0)
提交回复
热议问题