Set Focus After Last Character in Text Box

后端 未结 10 2360
梦谈多话
梦谈多话 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:47
    <script type="text/javascript">
        $(function(){
            $('#areaCode,#firstNum,#secNum').keyup(function(e){
                if($(this).val().length==$(this).attr('maxlength'))
                    $(this).next(':input').focus()
            })
        })
        </script>
    
    <body>
    
    <input type="text" id="areaCode" name="areaCode" maxlength="3" value="" size="3" />- 
    <input type="text" id="firstNum" name="firstNum" maxlength="3" value="" size="3" />- 
    <input type="text" id="secNum" name=" secNum " maxlength="4" value="" size="4" />
    
    </body>
    
    0 讨论(0)
  • 2020-11-27 14:49

    you can set pointer on last position of textbox as per following.

    temp=$("#txtName").val();
    $("#txtName").val('');
    $("#txtName").val(temp);
    $("#txtName").focus();
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 2020-11-27 14:55

    I tried lots of different solutions, the only one that worked for me was based on the solution by Chris G on this page (but with a slight modification).

    I have turned it into a jQuery plugin for future use for anyone that needs it

    (function($){
        $.fn.setCursorToTextEnd = function() {
            var $initialVal = this.val();
            this.val($initialVal);
        };
    })(jQuery);
    

    example of usage:

    $('#myTextbox').setCursorToTextEnd();
    
    0 讨论(0)
提交回复
热议问题