Search code examples
jqueryreplacedigits

Change digits for SSN with jquery


I found this script to hide digits for the SSN. I would like to accomplish what the blur/focus events do by toggling a button too (and for the text on the button to change as well). I attempted to do this with a Click event, but need help. Can someone please take a look at the fiddle.

I would also like for the HIDDEN state to show the last 4 digits of the SSN and the VISIBLE state shows all digits.

HTML
<form>
<input name="ssn" id="ssn" type="text">
<button id="submit">Show SSN</button>

jQuery          
var retrieveValue = function(ev){
    var $this = $(this),
        val = $this.data('value');

    if (val) {
        $this.val(val);
    }
},
hideValue = function(ev){
    var $this = $(this);

    $this.data('value', $this.val());
    $this.val($this.val().replace(/^\d{5}/, '*****'));
};

$('#ssn').focus(retrieveValue);

$('#ssn').blur(hideValue);

$("#submit").click(function () {
    // check the visibility of the next element in the DOM
    if ($(this).text("Hide SSN")) {
        $('#ssn').val(retrieveValue);
        } else {
       $('#ssn').val(hideValue);
       $('#submit').text("Show SSN");
    }
});

Click [here] (http://jsfiddle.net/squirc77/wEwYz/)


Solution

  • There is a much easier way of achieving this and it involves toggling the <input> from text to password

    JSFidlle 3 text fields

    HTML

    <input type="text" name="ssn1" id="ssn1" size="2" maxlength="3" style="text-align:center;" value="555">
    &nbsp;
    <input type="text" name="ssn2" id="ssn2" size="2" maxlength="2" style="text-align:center;" value="55">
    &nbsp;
    <input type="text" name="ssn3" id="ssn3" size="2" maxlength="4" style="text-align:center;" value="5555">
    &nbsp;
    <input type="button" id="ssn_button" value="Show/Hide SSN">
    

    JS

    $(document).ready(function(){
        // Page has loaded, hide SSN1 and SSN2
        $('#ssn1, #ssn2').attr({'type':'password'});
    
        // Listen for Focus on any three fields
        $('#ssn1, #ssn2, #ssn3').on('focus', function(){
            $('#ssn1, #ssn2').attr({'type':'text'});
        });
    
        // Listen for Blur on any three fields
        $('#ssn1, #ssn2, #ssn3').on('blur', function(){
            $('#ssn1, #ssn2').attr({'type':'password'});
        });
    
        // Show/Hide SSN click
        $('#ssn_button').on('click', function(){
            // Alternate SSN1 and SSN2 based on current SSN1 state
            if($('#ssn1').attr('type') == 'password'){
                $('#ssn1').attr({'type':'text'});
                $('#ssn2').attr({'type':'text'});
            }
            else{
                $('#ssn1').attr({'type':'password'});
                $('#ssn2').attr({'type':'password'});
            }
        });
    });
    

    Just for you OP :)

    JSFiddle 1 text field