Set Focus After Last Character in Text Box

JqueryFocus

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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

Solution 3 - Jquery

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

Solution 4 - Jquery

You should code like this.

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

  

Solution 5 - Jquery

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

Solution 6 - Jquery

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

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

Solution 7 - Jquery

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

Solution 8 - Jquery

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

Solution 9 - Jquery

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

Solution 10 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoshView Question on Stackoverflow
Solution 1 - JqueryChrisGView Answer on Stackoverflow
Solution 2 - JqueryGavin GView Answer on Stackoverflow
Solution 3 - JqueryDevasishView Answer on Stackoverflow
Solution 4 - JqueryArjunView Answer on Stackoverflow
Solution 5 - JqueryGuilhermeView Answer on Stackoverflow
Solution 6 - JqueryDensView Answer on Stackoverflow
Solution 7 - JquerySantosh SatapathyView Answer on Stackoverflow
Solution 8 - JquerymangasView Answer on Stackoverflow
Solution 9 - JqueryRajkumarView Answer on Stackoverflow
Solution 10 - JqueryPrateekView Answer on Stackoverflow