Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set mouse focus and move cursor to end of input using jQuery

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?

like image 736
jerodsanto Avatar asked Jun 29 '09 02:06

jerodsanto


People also ask

How do you move the cursor to the end?

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.

How do you move the cursor to the end of Contenteditable entity?

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.

How Stop focus in jQuery?

In jQuery by using blur() property we can remove focus from input textbox field.


2 Answers

Looks like clearing the value after focusing and then resetting works.

input.focus(); var tmpStr = input.val(); input.val(''); input.val(tmpStr); 
like image 200
scorpion9 Avatar answered Oct 04 '22 23:10

scorpion9


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.

like image 25
artlung Avatar answered Oct 04 '22 23:10

artlung