[jquery] Set Focus After Last Character in Text Box

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?

This question is related to jquery focus

The answer is


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

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

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 />

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

You should code like this.

var num = $('#Number').val();        
$('#Number').focus().val('').val(num);    

var val =$("#inputname").val();
$("#inputname").removeAttr('value').attr('value', val).focus();
// I think this is beter for all browsers...

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

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

temp=$("#txtName").val();
$("#txtName").val('');
$("#txtName").val(temp);
$("#txtName").focus();

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