74

I have 3 text boxes for a phone number. As the user types, it automatically moves from one textbox to the next. When the user presses backspace, I can move focus to the previous text box. The problem is that in IE, focus is set to the beginning of the text box. Here's my code, which works fine in chrome.

$('#AreaCode').live('keyup', function (event) {
    if ($(this).val().length == $(this).attr("maxlength"))
        $('#Prefix').focus();
});

$('#Prefix').live('keyup', function (event) {
    if (event.keyCode == 8 && $(this).val().length == 0)
        $('#AreaCode').focus();

    if ($(this).val().length == $(this).attr("maxlength"))
        $('#Number').focus();
});

$('#Number').live('keyup', function (event) {
    if (event.keyCode == 8 && $(this).val().length == 0)
        $('#Prefix').focus();
});

How do I make the focus set at the end of the contents when going backwards?

Josh
  • 16,286
  • 25
  • 113
  • 158
  • 1
    Duplicate of http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text-in-text-input-element – Alex Vidal Jan 05 '11 at 21:40
  • Another simple method here: http://stackoverflow.com/a/19568146/1032372 – shim Nov 25 '14 at 21:29

10 Answers10

99

This is the easy way to do it. If you're going backwards, just add $("#Prefix").val($("#Prefix").val()); after you set the focus

This is the more proper (cleaner) way:

function SetCaretAtEnd(elem) {
        var elemLen = elem.value.length;
        // For IE Only
        if (document.selection) {
            // Set focus
            elem.focus();
            // Use IE Ranges
            var oSel = document.selection.createRange();
            // Reset position to 0 & then set at end
            oSel.moveStart('character', -elemLen);
            oSel.moveStart('character', elemLen);
            oSel.moveEnd('character', 0);
            oSel.select();
        }
        else if (elem.selectionStart || elem.selectionStart == '0') {
            // Firefox/Chrome
            elem.selectionStart = elemLen;
            elem.selectionEnd = elemLen;
            elem.focus();
        } // if
    } // SetCaretAtEnd()
ChrisG
  • 1,403
  • 13
  • 22
  • Caret not Carat. I also wrapped it in a try..catch just in case, and put in "if (elemLen == 0) { return; }" near the start. Also the first line of your code isn't formatted like the rest. Other than that, thanks for the code :) – Anthony Oct 19 '11 at 16:19
  • 1
    Thanks for the spelling/formatting fix. I updated my answer to fix it. Glad it worked for you. – ChrisG Oct 19 '11 at 20:22
  • 4
    I added `elem = $(elem).get(0);` on line 2 before ` var elemLen = elem.value.length;`. If the object is a jQuery-object, it will be converted into a javascript-object. If it still is a javascript-object this line won't do anything because everything is fine :) This line avoids an error "elem.value is undefined". – ReynekeVosz Feb 03 '15 at 10:39
  • Worked for me - worth mentioning that you should chain the focus on the end of the val for efficiency – Liath Mar 26 '15 at 12:08
  • you copied this code from https://exceptionshub.com/set-focus-after-last-character-in-text-box.html .? – jasinth premkumar Dec 14 '17 at 13:22
55

I tried lots of different solutions, the only one that worked for me was based on the solution by Chris G on this page (but with a slight modification).

I have turned it into a jQuery plugin for future use for anyone that needs it

(function($){
    $.fn.setCursorToTextEnd = function() {
        var $initialVal = this.val();
        this.val($initialVal);
    };
})(jQuery);

example of usage:

$('#myTextbox').setCursorToTextEnd();
Community
  • 1
  • 1
Gavin G
  • 856
  • 6
  • 6
  • 2
    +1 For making this a plugin. Keep in mind to call `focus()` on the element before calling this function. – flu Sep 17 '12 at 10:23
  • 2
    This does not seem to work properly in IE, only FF. In IE, it goes back to the beginning of the text. Is anyone else experiencing this? – Paolo Broccardo Jan 13 '13 at 15:33
  • 2
    Why on earth have a dollar sign in front of JavaScript variables? Also, declare it with "var". – Mathias Lykkegaard Lorenzen Apr 09 '13 at 13:56
  • 3
    @MathiasLykkegaardLorenzen Putting dollar signs in front of jQuery variables is a practice recommended by some to distinguish jQuery vars from normal JS variables. In this instance it is completely unnecessary though, as this variable will only be available within the scope of the function, which is most evidently a jQuery func. –  Aug 25 '13 at 22:05
  • Thanks for clarifying it. To me though, it just confuses even more (especially if you mix it with PHP). But it is subjective I guess. – Mathias Lykkegaard Lorenzen Aug 29 '13 at 17:28
  • 7
    @gavin-g Awesome plugin. One update to make it a bit more cross browser. `this.val('').val(initialVal);` clearing the value first seems to help. – Bradmage Feb 06 '14 at 05:08
  • It seems this does not focus the input in latest FF. – fnagel Sep 11 '14 at 14:41
50

This works fine for me . [Ref: the very nice plug in by Gavin G]

(function($){
    $.fn.focusTextToEnd = function(){
        this.focus();
        var $thisVal = this.val();
        this.val('').val($thisVal);
        return this;
    }
}(jQuery));

$('#mytext').focusTextToEnd();
Devasish
  • 1,917
  • 2
  • 22
  • 32
27

You should code like this.

var num = $('#Number').val();        
$('#Number').focus().val('').val(num);    
K Scandrett
  • 16,390
  • 4
  • 40
  • 65
Arjun
  • 291
  • 3
  • 5
21

Code for any Browser:

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();
    }
}
Guilherme
  • 219
  • 2
  • 2
13

One can use these simple javascript within the input tag.

<input type="text" name="your_name" value="your_value"
     onfocus="this.setSelectionRange(this.value.length, this.value.length);" 
autofocus />
FULL STACK DEV
  • 15,207
  • 5
  • 46
  • 66
12

you can set pointer on last position of textbox as per following.

temp=$("#txtName").val();
$("#txtName").val('');
$("#txtName").val(temp);
$("#txtName").focus();
Dens
  • 459
  • 6
  • 7
2
var val =$("#inputname").val();
$("#inputname").removeAttr('value').attr('value', val).focus();
// I think this is beter for all browsers...
mangas
  • 464
  • 4
  • 8
1
<script type="text/javascript">
    $(function(){
        $('#areaCode,#firstNum,#secNum').keyup(function(e){
            if($(this).val().length==$(this).attr('maxlength'))
                $(this).next(':input').focus()
        })
    })
    </script>

<body>

<input type="text" id="areaCode" name="areaCode" maxlength="3" value="" size="3" />- 
<input type="text" id="firstNum" name="firstNum" maxlength="3" value="" size="3" />- 
<input type="text" id="secNum" name=" secNum " maxlength="4" value="" size="4" />

</body>
coolguy
  • 7,866
  • 9
  • 45
  • 71
Rajkumar
  • 11
  • 1
1

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();
Prateek
  • 1,229
  • 17
  • 31