Set mouse focus and move cursor to end of input using jQuery

后端 未结 19 1851
醉话见心
醉话见心 2020-12-04 06:42

This question has been asked in a few different formats but I can\'t get any of the answers to work in my scenario.

I am using jQuery to implement command history wh

相关标签:
19条回答
  • 2020-12-04 07:16

    Hope this help you:

    var fieldInput = $('#fieldName');
    var fldLength= fieldInput.val().length;
    fieldInput.focus();
    fieldInput[0].setSelectionRange(fldLength, fldLength);
    
    0 讨论(0)
  • 2020-12-04 07:22

    What about in one single line...

    $('#txtSample').focus().val($('#txtSample').val());
    

    This line works for me.

    0 讨论(0)
  • 2020-12-04 07:22

    Ref: @will824 Comment, This solution worked for me with no compatibility issues. Rest of solutions failed in IE9.

    var input = $("#inputID");
    var tmp = input.val();
    input.focus().val("").blur().focus().val(tmp);
    

    Tested and found working in:

    Firefox 33
    Chrome 34
    Safari 5.1.7
    IE 9
    
    0 讨论(0)
  • 2020-12-04 07:22

    The answer from scorpion9 works. Just to make it more clear see my code below,

    <script src="~/js/jquery.js"></script> 
    <script type="text/javascript">
        $(function () {
            var input = $("#SomeId");
            input.focus();
            var tmpStr = input.val();
            input.val('');
            input.val(tmpStr);
        });
    </script>
    
    0 讨论(0)
  • 2020-12-04 07:25

    I use code below and it works fine

    function to_end(el) {
                var len = el.value.length || 0;
                if (len) {
                    if ('setSelectionRange' in el) el.setSelectionRange(len, len);
                    else if ('createTextRange' in el) {// for IE
                        var range = el.createTextRange();
                        range.moveStart('character', len);
                        range.select();
                    }
                }
            }
    
    0 讨论(0)
  • 2020-12-04 07:25
        function focusCampo(id){
            var inputField = document.getElementById(id);
            if (inputField != null && inputField.value.length != 0){
                if (inputField.createTextRange){
                    var FieldRange = inputField.createTextRange();
                    FieldRange.moveStart('character',inputField.value.length);
                    FieldRange.collapse();
                    FieldRange.select();
                }else if (inputField.selectionStart || inputField.selectionStart == '0') {
                    var elemLen = inputField.value.length;
                    inputField.selectionStart = elemLen;
                    inputField.selectionEnd = elemLen;
                    inputField.focus();
                }
            }else{
                inputField.focus();
            }
        }
    
    $('#urlCompany').focus(focusCampo('urlCompany'));
    

    works for all ie browsers..

    0 讨论(0)
提交回复
热议问题