75

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?

2

10 Answers 10

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() 
Sign up to request clarification or add additional context in comments.

5 Comments

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 :)
Thanks for the spelling/formatting fix. I updated my answer to fix it. Glad it worked for you.
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".
Worked for me - worth mentioning that you should chain the focus on the end of the val for efficiency
you copied this code from exceptionshub.com/… .?
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(); 

7 Comments

+1 For making this a plugin. Keep in mind to call focus() on the element before calling this function.
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?
Why on earth have a dollar sign in front of JavaScript variables? Also, declare it with "var".
@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.
@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.
|
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(); 

1 Comment

@Gavin G version didn't work for me, but this one does.
27

You should code like this.

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

Comments

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

1 Comment

After trying loads of answers finally it worked ... :) I'm using IE 8.
14

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

Comments

12

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

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

Comments

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

Comments

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> 

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.