Josh Josh - 1 year ago 98
jQuery Question

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').live('keyup', function (event) {
if (event.keyCode == 8 && $(this).val().length == 0)

if ($(this).val().length == $(this).attr("maxlength"))

$('#Number').live('keyup', function (event) {
if (event.keyCode == 8 && $(this).val().length == 0)

How do I make the focus set at the end of the contents when going backwards?

Answer Source

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
            // 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);
        else if (elem.selectionStart || elem.selectionStart == '0') {
            // Firefox/Chrome
            elem.selectionStart = elemLen;
            elem.selectionEnd = elemLen;
        } // if
    } // SetCaretAtEnd()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download