How to set the cursor at the end in TEXTAREA? (not using jQuery)

Is there a way to position the cursor at the end in a TEXTAREA tag? I am using Firefox 3.6 and I do not need to work in IE or Chrome. JavaScript is fine, but it seems that all related answers here use the onfocus () event, which seems useless because when a user clicks anywhere in textarea, Firefox sets the cursor position there. I have long text to display in a text box, so that it displays the last part (which makes it easy to add something at the end).

+8
source share
7 answers

There can be many ways, for example

element.focus();
element.setSelectionRange(element.value.length,element.value.length);

http://jsfiddle.net/doktormolle/GSwfW/

+16
source

, javascript jQuery...

javascript , , , , textarea . jQuery :

$('textarea').focus(function() {
    var theVal = $(this).val();
    $(this).val(theVal);
});

javascript:

var theArea = document.getElementByName('[textareaname]');

theArea.onFocus = function(){
    var theVal = theArea.value;
    theArea.value = theVal;
}

. .

+5

function moveCaretToEnd(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();
    }
}

[Demo] []

+3
textarea.focus()
textarea.value+=' ';//adds a space at the end, scrolls it into view
+2
var t = /* get textbox element */ ;

t.onfocus = function () { 
    t.scrollTop = t.scrollHeight; 
    setTimeout(function(){ 
      t.select(); 
      t.selectionStart = t.selectionEnd; 
    }, 10); 
}

setTimeout () , ; ​​ script, ​​ - .

+1
(this.jQuery || this.Zepto).fn.focusEnd = function () {
    return this.each(function () {
        var val = this.value;
        this.focus();
        this.value = '';
        this.value = val;
    });
};
+1

@ . , U .

http://jsfiddle.net/70des6y2/

Sample:

document.getElementById("textarea").addEventListener("mousedown", e => {
  e.preventDefault();
  moveToEnd(e.target);
});
function moveToEnd(element) {
  element.focus();
  element.setSelectionRange(element.value.length, element.value.length);
}
0
source

All Articles