Set keyboard caret position in html textbox

后端 未结 9 2543
时光说笑
时光说笑 2020-11-22 00:02

Does anybody know how to move the keyboard caret in a textbox to a particular position?

For example, if a text-box (e.g. input element, not text-area) has 50 charact

相关标签:
9条回答
  • 2020-11-22 00:07
    function SetCaretEnd(tID) {
        tID += "";
        if (!tID.startsWith("#")) { tID = "#" + tID; }
        $(tID).focus();
        var t = $(tID).val();
        if (t.length == 0) { return; }
        $(tID).val("");
        $(tID).val(t);
        $(tID).scrollTop($(tID)[0].scrollHeight); }
    
    0 讨论(0)
  • 2020-11-22 00:07

    I would fix the conditions like below:

    function setCaretPosition(elemId, caretPos)
    {
     var elem = document.getElementById(elemId);
     if (elem)
     {
      if (typeof elem.createTextRange != 'undefined')
      {
       var range = elem.createTextRange();
       range.move('character', caretPos);
       range.select();
      }
      else
      {
       if (typeof elem.selectionStart != 'undefined')
        elem.selectionStart = caretPos;
       elem.focus();
      }
     }
    }
    
    0 讨论(0)
  • 2020-11-22 00:10

    Excerpted from Josh Stodola's Setting keyboard caret Position in a Textbox or TextArea with Javascript

    A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:

    function setCaretPosition(elemId, caretPos) {
        var elem = document.getElementById(elemId);
    
        if(elem != null) {
            if(elem.createTextRange) {
                var range = elem.createTextRange();
                range.move('character', caretPos);
                range.select();
            }
            else {
                if(elem.selectionStart) {
                    elem.focus();
                    elem.setSelectionRange(caretPos, caretPos);
                }
                else
                    elem.focus();
            }
        }
    }
    

    The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.

    Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari. Unfortunately on Safari it does not work in combination with the onfocus event).

    An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus:

    function addLoadEvent(func) {
        if(typeof window.onload != 'function') {
            window.onload = func;
        }
        else {
            if(func) {
                var oldLoad = window.onload;
    
                window.onload = function() {
                    if(oldLoad)
                            oldLoad();
    
                    func();
                }
            }
        }
    }
    
    // The setCaretPosition function belongs right here!
    
    function setTextAreasOnFocus() {
    /***
     * This function will force the keyboard caret to be positioned
     * at the end of all textareas when they receive focus.
     */
        var textAreas = document.getElementsByTagName('textarea');
    
        for(var i = 0; i < textAreas.length; i++) {
            textAreas[i].onfocus = function() {
                setCaretPosition(this.id, this.value.length);
            }
        }
    
        textAreas = null;
    }
    
    addLoadEvent(setTextAreasOnFocus);
    
    0 讨论(0)
  • 2020-11-22 00:13

    I've adjusted the answer of kd7 a little bit because elem.selectionStart will evaluate to false when the selectionStart is incidentally 0.

    function setCaretPosition(elem, caretPos) {
        var range;
    
        if (elem.createTextRange) {
            range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        } else {
            elem.focus();
            if (elem.selectionStart !== undefined) {
                elem.setSelectionRange(caretPos, caretPos);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:14

    If you need to focus some textbox and your only problem is that the entire text gets highlighted whereas you want the caret to be at the end, then in that specific case, you can use this trick of setting the textbox value to itself after focus:

    $("#myinputfield").focus().val($("#myinputfield").val());
    
    0 讨论(0)
  • 2020-11-22 00:15

    The link in the answer is broken, this one should work (all credits go to blog.vishalon.net):

    http://snipplr.com/view/5144/getset-cursor-in-html-textarea/

    In case the code gets lost again, here are the two main functions:

    function doGetCaretPosition(ctrl)
    {
     var CaretPos = 0;
    
     if (ctrl.selectionStart || ctrl.selectionStart == 0)
     {// Standard.
      CaretPos = ctrl.selectionStart;
     }
     else if (document.selection)
     {// Legacy IE
      ctrl.focus ();
      var Sel = document.selection.createRange ();
      Sel.moveStart ('character', -ctrl.value.length);
      CaretPos = Sel.text.length;
     }
    
     return (CaretPos);
    }
    
    
    function setCaretPosition(ctrl,pos)
    {
     if (ctrl.setSelectionRange)
     {
      ctrl.focus();
      ctrl.setSelectionRange(pos,pos);
     }
     else if (ctrl.createTextRange)
     {
      var range = ctrl.createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
     }
    }
    
    0 讨论(0)
提交回复
热议问题