SSN & ZIP

by 2Yootz

HTML

<div>
    <input type="text" maxlength="3" class="ssn-part-1" id="txtSsn1" />&nbsp;-
    <input type="text" maxlength="2" class="ssn-part-2" id="txtSsn2" />&nbsp;-
    <input type="text" maxlength="4" class="ssn-part-3" id="txtSsn3" />
</div>

<br />
<div style="border:1px solid #000;background-color:#FFFFCC;" id="results"></div>

CSS

.ssn-part-1 {
    width:30px;
}
.ssn-part-2 {
    width:20px;
}
.ssn-part-3 {
    width:35px;
}

JavaScript

$(function () {

    var lastchar;
    var last_position = 0;

    $(document).on("keyup", ".ssn-part-1", function () {
        var parent = $(this).parent();
        if ($(this).val().length == 3) {
            parent.find(".ssn-part-2").focus();
        }
    });

    $(document).on("keyup", ".ssn-part-2", function () {
        var parent = $(this).parent();
        if ($(this).val().length == 2) {
            parent.find(".ssn-part-3").focus();
        }
    });

    $(".ssn-part-1").bind("keydown click focus", function () {
        cursor_changed(this);
        $("#results").html(last_position);
    });


    $(document).on("keydown", "input[class^='ssn-part-']", function (e) {
        var e = window.event || e;
        var keyunicode = e.charCode || e.keyCode;

        //allow numbers, delete and backspace
        var validcodes = [8, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
        if (validcodes.indexOf(keyunicode) == -1) {
            return false;
        }
        lastchar = keyunicode;

    });


    function cursor_changed(element) {
        var new_position = getCursorPosition(element);
        if (new_position !== last_position) {
            last_position = new_position;
            return true
        }
        return false
    }

    function getCursorPosition(element) {
        var el = $(element).get(0);
        var pos = 0;
        if ('selectionStart' in el) {
            pos = el.selectionStart;
        } else if ('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }

})();