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 wh
Looks like clearing the value after focusing and then resetting works.
input.focus();
var tmpStr = input.val();
input.val('');
input.val(tmpStr);
I know this answer comes late, but I can see people havent found an answer. To prevent the up key to put the cursor at the start, just return false
from the method handling the event. This stops the event chain that leads to the cursor movement. Pasting revised code from the OP below:
$(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();
// HERE IS THE FIX:
return false;
// and it continues on from there
At the first you have to set focus on selected textbox object and next you set the value.
$('#inputID').focus();
$('#inputID').val('someValue')
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.
jQuery.fn.putCursorAtEnd = function() {
return this.each(function() {
$(this).focus()
// If this function exists...
if (this.setSelectionRange) {
// ... then use it (Doesn't work in IE)
// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
} else {
// ... otherwise replace the contents with itself
// (Doesn't work in Google Chrome)
$(this).val($(this).val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Google Chrome)
this.scrollTop = 999999;
});
};
Then you can just do:
input.putCursorAtEnd();
2 artlung's answer: It works with second line only in my code (IE7, IE8; Jquery v1.6):
var input = $('#some_elem');
input.focus().val(input.val());
Addition: if input element was added to DOM using JQuery, a focus is not set in IE. I used a little trick:
input.blur().focus().val(input.val());
I have found the same thing as suggested above by a few folks. If you focus()
first, then push the val()
into the input, the cursor will get positioned to the end of the input value in Firefox,Chrome and IE. If you push the val()
into the input field first, Firefox and Chrome position the cursor at the end, but IE positions it to the front when you focus()
.
$('element_identifier').focus().val('some_value')
should do the trick (it always has for me anyway).