0

I have a textbox and a button that serves as a mask/unmask button. It calls the checkSSN() function. By default, the text should be masked. But I need to have it in a certain format. SSN should be 9 alphanumeric characters. When it's masked, certain characters should be changed to 'X' (E.g. AF25QT34G to AXXXXT34G). The code below does the masking however I wanted it to do the masking while I'm still inputting. Also, how do I retrieve the original value to the code behind. Or is there any other way to make it convenient for me to do?

   function checkSSN(){
        if(ssn== undefined)
            var ssn= "";

        if(ssn == "")
            ssn = document.getElementById('<%= txtSSN.ClientID %>').value;
        var count = (document.getElementById('<%= txtSSN.ClientID %>').value.match(/X/g) || []).length;
        if(count > 1)
            showSSN(ssn);
        else
            hideSSN(ssn);
    }
    function hideSSN(ssn){
        var maskchar = 'X';
        var nonmaskdigit = 4;
        var firstpart = ssn.substring(0,1);
        var middlepart = maskchar.repeat(ssn.length - 5);
        var lastpart = ssn.substring(ssn.length - nonmaskdigit);
        var maskedSSN = firstpart + middlepart + lastpart;
        document.getElementById('<%= txtSSN.ClientID %>').value = ssn;
    }
    function showSSN(ssn){
        document.getElementById('<%= txtSSN.ClientID %>').value = ssn;
        ssn = "";
    }

1 Answers1

-1

Check this jsfiddle. I think this will solve your issue

http://jsfiddle.net/gtom9tvL/

$('.value').on('keydown keyup mousedown mouseup', function() {
         var res = this.value, //grabs the value
             len = res.length, //grabs the length
             max = 9, //sets a max chars
             stars = len>0?len>1?len>2?len>3?len>4?'XXX-XX-':'XXX-X':'XXX-':'XX':'X':'', //this provides the masking and formatting
            result = stars+res.substring(5); //this is the result
         $(this).attr('maxlength', max); //setting the max length
        $(".number").val(result); //spits the value into the input
    });

This is already answered in this Masking a social security number input

A Paul
  • 8,113
  • 3
  • 31
  • 61
  • How about if I don't want to have an input on top of another input? I want to use only one textbox and a button to show/hide the masked value. How will I get the original value? – user3062224 Sep 24 '19 at 07:46
  • I do not think you can do that, without storing the actual ssn number somewhere, now you can store that in your javascript or in another input box is your call, but you have to store the actual ssn somewhere to get that when you want. – A Paul Sep 24 '19 at 19:39