104

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?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
jerodsanto
  • 9,726
  • 8
  • 29
  • 23

20 Answers20

155

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

input.focus();
var tmpStr = input.val();
input.val('');
input.val(tmpStr);
Dan Abramov
  • 264,556
  • 84
  • 409
  • 511
scorpion9
  • 1,559
  • 1
  • 9
  • 2
  • 4
    This is the only solution I've been able to find that works cross-browser. Kudos to you! – Meshaal May 09 '12 at 01:16
  • 2
    This works fine with FF and chrome but not in IE.. any one know how to solve this issue in IE ? – john Smith Sep 20 '12 at 13:35
  • 1
    Note also you can chain the calls: `var temp = input.focus().val(); input.val('').val(temp);` – harpo Feb 22 '14 at 04:40
  • 25
    This can get even simpler: `input.focus().val(input.val());` – Fateh Khalsa May 30 '14 at 18:10
  • Nice solution. Works as expected and cross browser. And works on multiple input types, awesome. Thanks! – EHerman Nov 19 '14 at 18:24
  • @FatehKhalsa this doesn't work for me. The value needs to change for the cursor to move. harpo's method works! – Henridv Jan 14 '15 at 10:33
  • 2
    Doesn't seem to work with `contenteditable` elements for some reason, maybe as one has to use `.html()` rather than `.val()` – jg2703 May 03 '17 at 15:11
  • doesn't work with `divs` or maybe it's simply because they're `contentEditable` like @joel2703 pointed out – oldboy Dec 25 '17 at 19:25
  • 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. – albertrw Sep 03 '21 at 18:47
56

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.

artlung
  • 33,305
  • 16
  • 69
  • 121
  • 1
    Yes, input is an element. I tried this and it didn't work in FF3 or Safari 4 – jerodsanto Jun 29 '09 at 12:52
  • Any update on this? Worked for me. Update question or add an answer if you found a solution. – artlung Jul 14 '09 at 22:53
  • 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? – JochenJung Sep 11 '12 at 10:49
  • @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. – artlung Sep 11 '12 at 12:44
52

Hope this help you:

var fieldInput = $('#fieldName');
var fldLength= fieldInput.val().length;
fieldInput.focus();
fieldInput[0].setSelectionRange(fldLength, fldLength);
Douwe de Haan
  • 6,247
  • 1
  • 30
  • 45
harsh4u
  • 2,550
  • 4
  • 24
  • 39
  • 4
    Works fine, I think this is a better solution than resetting the value, especially when there's some kind of model-view-binding. – morten.c Sep 05 '16 at 12:53
  • 2
    This is the right answer, setting exactly what you want to set without kludging it. – Dan Barron Apr 18 '19 at 13:02
  • this solution is no longer working. it give "Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable" – Ad Kahn Jun 16 '23 at 16:26
16

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();
jackocnr
  • 17,068
  • 10
  • 54
  • 63
13

Ref: @will824 Comment, This solution worked for me with no compatibility issues. Rest of solutions failed in IE9.

var input = $("#inputID");
var tmp = input.val();
input.focus().val("").blur().focus().val(tmp);

Tested and found working in:

Firefox 33
Chrome 34
Safari 5.1.7
IE 9
Jean-Paul
  • 19,910
  • 9
  • 62
  • 88
Aamir Shahzad
  • 6,683
  • 8
  • 47
  • 70
12

What about in one single line...

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

This line works for me.

Chris Rosete
  • 1,240
  • 15
  • 13
8

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());
SergO
  • 2,703
  • 1
  • 30
  • 23
  • 1
    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); – will824 Jan 22 '13 at 22:18
6

It will be different for different browsers:

This works in ff:

    var t =$("#INPUT");
    var l=$("#INPUT").val().length;
    $(t).focus();

    var r = $("#INPUT").get(0).createTextRange();
    r.moveStart("character", l); 
    r.moveEnd("character", l);      
    r.select();

More details are in these articles here at SitePoint, AspAlliance.

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
6

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
pederOverland
  • 860
  • 6
  • 8
6

I use code below and it works fine

function to_end(el) {
            var len = el.value.length || 0;
            if (len) {
                if ('setSelectionRange' in el) el.setSelectionRange(len, len);
                else if ('createTextRange' in el) {// for IE
                    var range = el.createTextRange();
                    range.moveStart('character', len);
                    range.select();
                }
            }
        }
Tomas
  • 17,551
  • 43
  • 152
  • 257
4

like other said, clear and fill worked for me:

    var elem = $('#input_field');
    var val = elem.val();
    elem.focus().val('').val(val);
Fabrizio
  • 3,734
  • 2
  • 29
  • 32
3

set the value first. then set the focus. when it focuses, it will use the value that exists at the time of focus, so your value must be set first.

this logic works for me with an application that populates an <input> with the value of a clicked <button>. val() is set first. then focus()

$('button').on('click','',function(){
    var value = $(this).attr('value');
    $('input[name=item1]').val(value);
    $('input[name=item1]').focus();
});
  • U can make it more simple one line instead of two: `$('input[name=item1]').val(value).focus();` – inMILD Jul 08 '18 at 04:53
2

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).

Hari
  • 1,509
  • 15
  • 34
2

At the first you have to set focus on selected textbox object and next you set the value.

$('#inputID').focus();
$('#inputID').val('someValue')
hladas
  • 21
  • 1
2
    function focusCampo(id){
        var inputField = document.getElementById(id);
        if (inputField != null && inputField.value.length != 0){
            if (inputField.createTextRange){
                var FieldRange = inputField.createTextRange();
                FieldRange.moveStart('character',inputField.value.length);
                FieldRange.collapse();
                FieldRange.select();
            }else if (inputField.selectionStart || inputField.selectionStart == '0') {
                var elemLen = inputField.value.length;
                inputField.selectionStart = elemLen;
                inputField.selectionEnd = elemLen;
                inputField.focus();
            }
        }else{
            inputField.focus();
        }
    }

$('#urlCompany').focus(focusCampo('urlCompany'));

works for all ie browsers..

madhu
  • 244
  • 5
  • 13
1

Here is another one, a one liner which does not reassign the value:

$("#inp").focus()[0].setSelectionRange(99999, 99999);
Chong Lip Phang
  • 8,755
  • 5
  • 65
  • 100
0
function CurFocus()
{
    $('.txtEmail').focus(); 
}

function pageLoad()
{
   setTimeout(CurFocus(),3000);
}

window.onload = pageLoad;
xdazz
  • 158,678
  • 38
  • 247
  • 274
abbijohn
  • 1
  • 1
0

The answer from scorpion9 works. Just to make it more clear see my code below,

<script src="~/js/jquery.js"></script> 
<script type="text/javascript">
    $(function () {
        var input = $("#SomeId");
        input.focus();
        var tmpStr = input.val();
        input.val('');
        input.val(tmpStr);
    });
</script>
Diganta Kumar
  • 3,637
  • 3
  • 27
  • 29
0
  var prevInputVal = $('#input_id').val();
  $('#input_id').val('').focus().val(prevInputVal)

Store input previous value in a variable -> empty input value -> focus input -> reassign original value SIMPLE !

-4

It will focus with mouse point

$("#TextBox").focus();

Pergin Sheni
  • 393
  • 2
  • 11