简体   繁体   中英

move caret to end of textarea on focus

I thought this would be quite a simple thing to do but I can't get it to work. I am using the following code but with no success. I know this does not work in ie, I am using chrome. here is a jsFiddle to demonstrate. Thanks

$('#ta').focus(function(){
  this.selectionStart = this.value.length;
});

This is a cross-browser and jQuery compliant solution (it supports multiple elements in a given selector).

Tested in Chrome 40x, IE 11, and FireFox 34x

 $("textarea").focus(function () { for (var i = 0; i < $(this).length; i++) { var el = $(this)[i] window.setTimeout(function () { if (el !== null) { if (el.createTextRange) { var range = el.createTextRange(); range.move('character', el.value.length); range.select(); } else { if (el.selectionStart || el.selectionStart === 0) { el.focus(); el.setSelectionRange(el.value.length, el.value.length); } else { el.focus(); } } } }, 1) } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <textarea id="ta">focus on me</textarea><br /> <textarea id="ta2">focus on me</textarea> 

Just in case you wanted to see how to fix you original solution so that it may work, here is what you had to do:

$('#ta').focus(function (e) {
    var element = this;
    setTimeout(function () {
        element.selectionStart = element.value.length;
    }, 1);
});

The position must be set after a very short delay (1 millisecond is sufficient in my case) because it seems as though the cursors position is set to where you click after the focus function is finished, so you are setting the cursor to be at the end of the input but then it is immediately being placed where the user clicked right after this happens

Fiddle: http://jsfiddle.net/zb5uoL3t/

a quick one

$('#ta').focus(function(){
    moveCursorToEnd(document.getElementById('ta'));
});

function moveCursorToEnd(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}

http://jsfiddle.net/9xaxz53x/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM