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

165,731

Solution 1

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

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

Solution 2

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.

Solution 3

Hope this help you:

var fieldInput = $('#fieldName');
var fldLength= fieldInput.val().length;
fieldInput.focus();
fieldInput[0].setSelectionRange(fldLength, fldLength);

Solution 4

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();

Solution 5

What about in one single line...

$('#txtSample').focus().val($('#txtSample').val());

This line works for me.

Share:
165,731

Related videos on Youtube

jerodsanto
Author by

jerodsanto

I love lamp.

Updated on December 23, 2021

Comments

  • jerodsanto
    jerodsanto over 2 years

    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?

  • jerodsanto
    jerodsanto almost 15 years
    Yes, input is an <input> element. I tried this and it didn't work in FF3 or Safari 4
  • artlung
    artlung almost 15 years
    Any update on this? Worked for me. Update question or add an answer if you found a solution.
  • Meshaal
    Meshaal about 12 years
    This is the only solution I've been able to find that works cross-browser. Kudos to you!
  • JochenJung
    JochenJung over 11 years
    In FF15 this sets the cursor to the begin of the input field. Other than that its working fine. Do you have a solution for FF as well?
  • artlung
    artlung over 11 years
    @JochenJung I have not looked at this since 2009 - it worked then with FF3 and jQuery. If you come up with a solution using current jQuery and FF15, please feel free to edit this post.
  • john Smith
    john Smith over 11 years
    This works fine with FF and chrome but not in IE.. any one know how to solve this issue in IE ?
  • will824
    will824 over 11 years
    This kind of worked for me, but I had to do something like: var input = $("#inputID"); tmp = input.val(); input.focus().val("").blur().focus().val(tmp);
  • Rupam Datta
    Rupam Datta over 10 years
    I tried this but doesnot work. Does it also work for you with a div content editable set to true?
  • harpo
    harpo about 10 years
    Note also you can chain the calls: var temp = input.focus().val(); input.val('').val(temp);
  • Fateh Khalsa
    Fateh Khalsa almost 10 years
    This can get even simpler: input.focus().val(input.val());
  • EHerman
    EHerman over 9 years
    Nice solution. Works as expected and cross browser. And works on multiple input types, awesome. Thanks!
  • Henridv
    Henridv over 9 years
    @FatehKhalsa this doesn't work for me. The value needs to change for the cursor to move. harpo's method works!
  • morten.c
    morten.c over 7 years
    Works fine, I think this is a better solution than resetting the value, especially when there's some kind of model-view-binding.
  • Gone Coding
    Gone Coding over 7 years
    You can reduce second line to var key = e.charCode || e.keyCode || 0;
  • jg2703
    jg2703 about 7 years
    Doesn't seem to work with contenteditable elements for some reason, maybe as one has to use .html() rather than .val()
  • oldboy
    oldboy over 6 years
    doesn't work with divs or maybe it's simply because they're contentEditable like @joel2703 pointed out
  • inMILD
    inMILD almost 6 years
    U can make it more simple one line instead of two: $('input[name=item1]').val(value).focus();
  • Dan Barron
    Dan Barron about 5 years
    This is the right answer, setting exactly what you want to set without kludging it.
  • AdamJones
    AdamJones about 4 years
    Amazing thanks, only solution I've found come 2020 that seems to work reliably.
  • albertrw
    albertrw over 2 years
    Worked for me, thanks. Is it just me or is it absolutely mind-blowing that JS/Jquery don't have a specific function that does this? These methods don't seem efficient and it has to be a very common action.