Use JavaScript to place cursor at end of text in text input element

后端 未结 30 3357
时光说笑
时光说笑 2020-11-22 02:48

What is the best way (and I presume simplest way) to place the cursor at the end of the text in a input text element via JavaScript - after focus has been set to the element

相关标签:
30条回答
  • 2020-11-22 03:38

    There's a simple way to get it working in most browsers.

    this.selectionStart = this.selectionEnd = this.value.length;
    

    However, due to the *quirks of a few browsers, a more inclusive answer looks more like this

    setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
    

    Using jQuery (to set the listener, but it's not necessary otherwise)

    $('#el').focus(function(){
      var that = this;
      setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input id='el' type='text' value='put cursor at end'>

    Using Vanilla JS (borrowing addEvent function from this answer)

    // Basic cross browser addEvent
    function addEvent(elem, event, fn){
    if(elem.addEventListener){
      elem.addEventListener(event, fn, false);
    }else{
      elem.attachEvent("on" + event,
      function(){ return(fn.call(elem, window.event)); });
    }}
    var element = document.getElementById('el');
    
    addEvent(element,'focus',function(){
      var that = this;
      setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
    });
    <input id='el' type='text' value='put cursor at end'>


    Quirks

    Chrome has an odd quirk where the focus event fires before the cursor is moved into the field; which screws my simple solution up. Two options to fix this:

    1. You can add a timeout of 0 ms (to defer the operation until the stack is clear)
    2. You can change the event from focus to mouseup. This would be pretty annoying for the user unless you still kept track of focus. I'm not really in love with either of these options.

    Also, @vladkras pointed out that some older versions of Opera incorrectly calculate the length when it has spaces. For this you can use a huge number that should be larger than your string.

    0 讨论(0)
  • 2020-11-22 03:39

    I faced this same issue (after setting focus through RJS/prototype) in IE. Firefox was already leaving the cursor at the end when there is already a value for the field. IE was forcing the cursor to the beginning of the text.

    The solution I arrived at is as follows:

    <input id="search" type="text" value="mycurrtext" size="30" 
           onfocus="this.value = this.value;" name="search"/>
    

    This works in both IE7 and FF3

    0 讨论(0)
  • 2020-11-22 03:40

    el.setSelectionRange(-1, -1);

    https://codesandbox.io/s/peaceful-bash-x2mti

    This method updates the HTMLInputElement.selectionStart, selectionEnd, and selectionDirection properties in one call.

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange

    In other js methods -1 usually means (to the) last character. This is the case for this one too, but I couldn't find explicit mention of this behavior in the docs.

    0 讨论(0)
  • 2020-11-22 03:41

    Try this, it has worked for me:

    //input is the input element
    
    input.focus(); //sets focus to element
    var val = this.input.value; //store the value of the element
    this.input.value = ''; //clear the value of the element
    this.input.value = val; //set that value back.  
    

    For the cursor to be move to the end, the input has to have focus first, then when the value is changed it will goto the end. If you set .value to the same, it won't change in chrome.

    0 讨论(0)
  • 2020-11-22 03:42

    For all browsers for all cases:

    function moveCursorToEnd(el) {
        window.setTimeout(function () {
                if (typeof el.selectionStart == "number") {
                el.selectionStart = el.selectionEnd = el.value.length;
            } else if (typeof el.createTextRange != "undefined") {
                var range = el.createTextRange();
                range.collapse(false);
                range.select();
            }
        }, 1);
    }
    

    Timeout required if you need to move cursor from onFocus event handler

    0 讨论(0)
  • 2020-11-22 03:42

    Check this solution!

    //fn setCurPosition
    $.fn.setCurPosition = function(pos) {
        this.focus();
        this.each(function(index, elem) {
            if (elem.setSelectionRange) {
                elem.setSelectionRange(pos, pos);
            } else if (elem.createTextRange) {
                var range = elem.createTextRange();
                range.collapse(true);
                range.moveEnd('character', pos);
                range.moveStart('character', pos);
                range.select();
            }
        });
        return this;
    };
    
    // USAGE - Set Cursor ends
    $('#str1').setCurPosition($('#str1').val().length);
    
    // USAGE - Set Cursor at 7 position
    // $('#str2').setCurPosition(7);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <p>Set cursor at any position</p>
    <p><input type="text" id="str1" value="my string here" /></p>
    <p><input type="text" id="str2" value="my string here" /></p>

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