John Cooper John Cooper - 7 months ago 31
Javascript Question

Autoformat SSN while entering the number

I have a textfield and the user enters the SSN number. While entering itself it should format. Like On the change of the textField... it should format

999-999-999
in this way on the display itself.

Answer
<input id="ssn"/>

<script type="text/javascript">
    $('#ssn').keyup(function() {
        var val = this.value.replace(/\D/g, '');
        var newVal = '';
        while (val.length > 3) {
          newVal += val.substr(0, 3) + '-';
          val = val.substr(3);
        }
        newVal += val;
        this.value = newVal;
    });
</script>