This question has been asked in a few different formats but I can't get any of the answers to work in my scenario.
I am using jQuery to implement command history when user hits up/down arrows. When up arrow is hit, I replace the input value with previous command and set focus on the input field, but want the cursor always to be positioned at the end of the input string.
My code, as is:
$(document).keydown(function(e) {
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
var input = self.shell.find('input.current:last');
switch(key) {
case 38: // up
lastQuery = self.queries[self.historyCounter-1];
self.historyCounter--;
input.val(lastQuery).focus();
// and it continues on from there
How can I force the cursor to be placed at the end of 'input' after focus?
Looks like clearing the value after focusing and then resetting works.
Chris Coyier has a mini jQuery plugin for this which works perfectly well: http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/
It uses setSelectionRange if supported, else has a solid fallback.
Then you can just do:
At the first you have to set focus on selected textbox object and next you set the value.
It looks a little odd, even silly, but this is working for me:
Now, I'm not certain I've replicated your setup. I'm assuming
input
is an<input>
element.By re-setting the value (to itself) I think the cursor is getting put at the end of the input. Tested in Firefox 3 and MSIE7.
2 artlung's answer: It works with second line only in my code (IE7, IE8; Jquery v1.6):
Addition: if input element was added to DOM using JQuery, a focus is not set in IE. I used a little trick:
Hope this help you: