Putting cursor at end of textbox in javascript

前端 未结 3 926
野趣味
野趣味 2021-01-18 02:07

I have a textbox that when I put on focus I want the cursor to goto the end of the textbox.

The solution that keeps coming up is just

this.value = t         


        
3条回答
  •  情话喂你
    2021-01-18 02:38

    You need to move the caret using either the selectionStart and selectionEnd properties or setSelectionRange() method of the input. IE < 9 does not support these though, so you need to use the input's createTextRange() method in those browsers.

    Code:

    function moveCaretToEnd(el) {
        el.focus();
        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();
        }
    }
    

提交回复
热议问题