2

$(id).focus(); sets the cursor position to the beginning of an input box, but I'd like to place it at the end of the text, in the last row and at the last position.

halfer
  • 19,824
  • 17
  • 99
  • 186
nrsharma
  • 2,532
  • 3
  • 20
  • 36

2 Answers2

1

You can use setSelectionRange for this

My code -

HTML -

<textarea rows="8" id="txt1" style="width:400px;" >Hello Hello Hello Hello</textarea>

Jquery -

var input = $("#txt1");
var len = input.val().length;
input[0].focus();
input[0].setSelectionRange(len, len);

Try -

Example

Ishan Jain
  • 8,063
  • 9
  • 48
  • 75
  • You should post the code you're actually using **here** as well, not just a jsFiddle – Ian Jun 29 '13 at 04:55
0

Try this:

$(document).ready(function(){
        $("#search").focus(function(){
            if (this.setSelectionRange)
            {
            var len = $(this).val().length;
            this.setSelectionRange(len, len);
            }
            else
            {
            $(this).val($(this).val());
            }

    });

    $("#search").focus();
    });

Demo with input

Demo with textarea

Because setSelectionRange is not supported by all browsers. So the best solution is to combine setSelectionRange with $(this).val($(this).val());. For more information, check out: Use JavaScript to place cursor at end of text in text input element

Community
  • 1
  • 1
Khanh TO
  • 48,509
  • 13
  • 99
  • 115