Set Focus to End of Text Input using Javascript and jQuery

If the text input already has some text and you wish to set the cursor to the end of the text input then here’s how it can be done.

Using JavaScript

In javascript simply add a onfocus event handler in the text input.

<input type="text" onfocus="this.value = this.value;" value="Some text"/>

Using jQuery

Define a function as follows.

(function ($) {
    $.fn.focusTextToEnd = function () {
        this.focus();
        var $thisVal = this.val();
        this.val('').val($thisVal);
        return this;
    }
}(jQuery));

And use it as,

$('#some-input').focusTextToEnd();

This content has been helpful to you?

Thanks for contributing!

Yes No