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?
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();
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With