Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

masking numbers to a special character (*) in input

Tags:

jquery

masking

I am trying to mask all the numbers in SSN field to * while keeping user only enter numeric values and formatting the SSN with dashes.

Here is a fiddle link:

https://jsfiddle.net/7f8p83am/

$('#ssn').keyup(function() {
    var val = this.value.replace(/\D/g, '');
    var newVal = '';
    var sizes = [3, 2, 4];
    var maxSize = 10;

    for (var i in sizes) {
      if (val.length > sizes[i]) {
        newVal += val.substr(0, sizes[i]) + '-';
        val = val.substr(sizes[i]);
      } else { 
        break; 
      }       
    }

    newVal += val;
    this.value = newVal;  
});   

Obviously, the replace is getting rid of *. Any ideas on how to do this?

thanks in advance.

like image 475
CFNinja Avatar asked May 25 '16 15:05

CFNinja


1 Answers

You could consider removing all non-digits and asterisks as they were entered and replacing digits with asterisk :

// Remove all non-digits/asterisks and replace digits with asterisks
var val = this.value.replace(/[^\d\*]/g, '').replace(/\d/g,'*');

Additionally, you may want to try adding a maxlength attribute on your element as well to prevent it from continuing :

<input id='ssn' maxlength='11'/>

Finally, you will likely want to consider storing a hidden field or variable that will store your proper SSN value so that you can post it to the server as expected.

Example

enter image description here

<!DOCTYPE html>
<html>

<head>
  <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>

<body>
  <input id='ssn' maxlength='11' />
  <script>
    $(function() {
      $('#ssn').keyup(function() {
        var val = this.value.replace(/[^\d\*]/g, '').replace(/\d/g, '*');
        var newVal = '';
        var sizes = [3, 2, 4];
        var maxSize = 10;

        for (var i in sizes) {
          if (val.length > sizes[i]) {
            newVal += val.substr(0, sizes[i]) + '-';
            val = val.substr(sizes[i]);
          } else {
            break;
          }
        }

        newVal += val;
        this.value = newVal;
      });
    });
  </script>
</body>

</html>
like image 94
Rion Williams Avatar answered Oct 01 '22 20:10

Rion Williams