$(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.
Asked
Active
Viewed 1,473 times
2 Answers
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 -

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();
});
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
-
-
-
1
-
@nrsharma: i think the problem is with the browser. `setSelectionRange` as in Ishan Jain's answer is also the solution. But `setSelectionRange` is not supported by all browsers. I think the best way is to combine this solution with `setSelectionRange` – Khanh TO Jun 29 '13 at 04:48
-
well, you are right setSelectionRange is not working with all browsers. – nrsharma Jun 29 '13 at 04:51
-
-
@Khanh: it's nice solution, but "setSelectionRange" working in all major browsers(FF, IE and Chrome). – Ishan Jain Jun 29 '13 at 05:11
-
@Ishan Jain:check browser compatibility in this link: https://developer.mozilla.org/en-US/docs/Web/API/Input.setSelectionRange – Khanh TO Jun 29 '13 at 05:12
-
@Khanh: Yes, you are right. But i checked it in IE10, Chrome27 and it's working – Ishan Jain Jun 29 '13 at 05:16