Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...