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

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

    Set cursor at any position

提交回复
热议问题