How can you move the cursor to the last position of a textarea in Javascript?

sol picture sol · Mar 12, 2009 · Viewed 44.5k times · Source

I have a textarea and a button on a form. The textarea may already have some text in it. I would like the cursor to move to the last position in the text area when the button is clicked.

Is this possible?

Answer

mkaj picture mkaj · Aug 1, 2012

xgMz's answer was best for me. You don't need to worry about the browser:

var html = $("#MyTextArea").val();
$("#MyTextArea").focus().val("").val(html);

And here's a quick jQuery extension I wrote to do this for me next time:

; (function($) {
    $.fn.focusToEnd = function() {
        return this.each(function() {
            var v = $(this).val();
            $(this).focus().val("").val(v);
        });
    };
})(jQuery);

Use like this:

$("#MyTextArea").focusToEnd();