Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Focus After Last Character in Text Box

Tags:

jquery

focus

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?

like image 593
Josh Avatar asked Jan 05 '11 21:01

Josh


Video Answer


2 Answers

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(); 
like image 24
Gavin G Avatar answered Sep 19 '22 00:09

Gavin G


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() 
like image 194
ChrisG Avatar answered Sep 17 '22 00:09

ChrisG