Set Focus After Last Character in Text Box

后端 未结 10 2406
梦谈多话
梦谈多话 2020-11-27 13:54

I have 3 text boxes for a phone number. As the user types, it automatically moves from one textbox to the next. When the user presses backspace, I can move focus to the pr

10条回答
  •  再見小時候
    2020-11-27 14:52

    This is the easy way to do it. If you're going backwards, just add $("#Prefix").val($("#Prefix").val()); after you set the focus

    This is the more proper (cleaner) way:

    function SetCaretAtEnd(elem) {
            var elemLen = elem.value.length;
            // For IE Only
            if (document.selection) {
                // Set focus
                elem.focus();
                // Use IE Ranges
                var oSel = document.selection.createRange();
                // Reset position to 0 & then set at end
                oSel.moveStart('character', -elemLen);
                oSel.moveStart('character', elemLen);
                oSel.moveEnd('character', 0);
                oSel.select();
            }
            else if (elem.selectionStart || elem.selectionStart == '0') {
                // Firefox/Chrome
                elem.selectionStart = elemLen;
                elem.selectionEnd = elemLen;
                elem.focus();
            } // if
        } // SetCaretAtEnd()
    

提交回复
热议问题