$(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.
2 Answers
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 -
-
You should post the code you're actually using here as well, not just a jsFiddle– IanJun 29, 2013 at 4:55
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
-
-
-
1it's not working with <textarea>. It's setting the curosr at the beginning.– nrsharmaJun 29, 2013 at 4:44
-
@nrsharma: i think the problem is with the browser.
setSelectionRange
as in Ishan Jain's answer is also the solution. ButsetSelectionRange
is not supported by all browsers. I think the best way is to combine this solution withsetSelectionRange
– Khanh TOJun 29, 2013 at 4:48 -
well, you are right setSelectionRange is not working with all browsers.– nrsharmaJun 29, 2013 at 4:51