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

jerodsanto picture jerodsanto · Jun 29, 2009 · Viewed 152.3k times · Source

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?

Answer

scorpion9 picture scorpion9 · Dec 25, 2011

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

input.focus();
var tmpStr = input.val();
input.val('');
input.val(tmpStr);