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?
To move the cursor to the end of an input field: Use the setSelectionRange() method to set the current text selection position to the end of the input field. Call the focus() method on the input element. The focus method will move the cursor to the end of the input element's value.
selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range range. collapse(false);//collapse the range to the end point. false means collapse to end rather than the start selection = window. getSelection();//get the selection object (allows you to change selection) selection.
In jQuery by using blur() property we can remove focus from input textbox field.
Looks like clearing the value after focusing and then resetting works.
input.focus(); var tmpStr = input.val(); input.val(''); input.val(tmpStr);
It looks a little odd, even silly, but this is working for me:
input.val(lastQuery); input.focus().val(input.val());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With