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

后端 未结 30 3371
时光说笑
时光说笑 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: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();
        }
    }
    

提交回复
热议问题