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

后端 未结 30 3402
时光说笑
时光说笑 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:44

    If the input field just needs a static default value I usually do this with jQuery:

    $('#input').focus().val('Default value');
    

    This seems to work in all browsers.

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

    I just found that in iOS, setting textarea.textContent property will place the cursor at the end of the text in the textarea element every time. The behavior was a bug in my app, but seems to be something that you could use intentionally.

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

    Though I'm answering too late, but for future query, it will be helpful. And it also work in contenteditable div.

    From where you need to set focus at end; write this code-

    var el = document.getElementById("your_element_id");
    placeCaretAtEnd(el);
    

    And the function is -

    function placeCaretAtEnd(el) {
        el.focus();
        if (typeof window.getSelection != "undefined"
                && typeof document.createRange != "undefined") {
            var range = document.createRange();
            range.selectNodeContents(el);
            range.collapse(false);
            var sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (typeof document.body.createTextRange != "undefined") {
            var textRange = document.body.createTextRange();
            textRange.moveToElementText(el);
            textRange.collapse(false);
            textRange.select();
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:47

    While this may be an old question with lots of answers, I ran across a similar issue and none of the answers were quite what I wanted and/or were poorly explained. The issue with selectionStart and selectionEnd properties is that they don't exist for input type number (while the question was asked for text type, I reckon it might help others who might have other input types that they need to focus). So if you don't know whether the input type the function will focus is a type number or not, you cannot use that solution.

    The solution that works cross browser and for all input types is rather simple:

    • get and store the value of input in a variable
    • focus the input
    • set the value of input to the stored value

    That way the cursor is at the end of the input element.
    So all you'd do is something like this (using jquery, provided the element selector that one wishes to focus is accessible via 'data-focus-element' data attribute of the clicked element and the function executes after clicking on '.foo' element):

    $('.foo').click(function() {
        element_selector = $(this).attr('data-focus-element');
        $focus = $(element_selector);
        value = $focus.val();
        $focus.focus();
        $focus.val(value);
    });
    

    Why does this work? Simply, when the .focus() is called, the focus will be added to the beginning of the input element (which is the core problem here), ignoring the fact, that the input element already has a value in it. However, when the value of an input is changed, the cursor is automatically placed at the end of the value inside input element. So if you override the value with the same value that had been previously entered in the input, the value will look untouched, the cursor will, however, move to the end.

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

    I wanted to put cursor at the end of a "div" element where contenteditable = true, and I got a solution with Xeoncross code:

    <input type="button" value="Paste HTML" onclick="document.getElementById('test').focus(); pasteHtmlAtCaret('<b>INSERTED</b>'); ">
    
    <div id="test" contenteditable="true">
        Here is some nice text
    </div>
    

    And this function do magic:

     function pasteHtmlAtCaret(html) {
        var sel, range;
        if (window.getSelection) {
            // IE9 and non-IE
            sel = window.getSelection();
            if (sel.getRangeAt && sel.rangeCount) {
                range = sel.getRangeAt(0);
                range.deleteContents();
    
                // Range.createContextualFragment() would be useful here but is
                // non-standard and not supported in all browsers (IE9, for one)
                var el = document.createElement("div");
                el.innerHTML = html;
                var frag = document.createDocumentFragment(), node, lastNode;
                while ( (node = el.firstChild) ) {
                    lastNode = frag.appendChild(node);
                }
                range.insertNode(frag);
    
                // Preserve the selection
                if (lastNode) {
                    range = range.cloneRange();
                    range.setStartAfter(lastNode);
                    range.collapse(true);
                    sel.removeAllRanges();
                    sel.addRange(range);
                }
            }
        } else if (document.selection && document.selection.type != "Control") {
            // IE < 9
            document.selection.createRange().pasteHTML(html);
        }
    }
    

    Works fine for most browsers, please check it, this code puts text and put focus at the end of the text in div element (not input element)

    https://jsfiddle.net/Xeoncross/4tUDk/

    Thanks, Xeoncross

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

    Super easy (you may have to focus on the input element)

    inputEl = getElementById('inputId');
    var temp = inputEl.value;
    inputEl.value = '';
    inputEl.value = temp;
    
    0 讨论(0)
提交回复
热议问题