zazvorniki
zazvorniki

Reputation: 3602

Customizable jquery mask

I've been playing with a masking function to allow users to type in numbers and it masks them out based on a certain pattern.

For example they type 123456789, but it appears in the field as XXX-XX-6789

Right now I have it hard coded to one pattern, but I would like to expand this to allow them to choose what ever pattern they wish. This is mainly if a client has a loyalty card or something along those lines. Is there a simple way of doing this without hard coding each pattern I think they may want?

My html

<p class="maskNum">
  <input type="text" class="form-control mask" autocomplete="off" maxlengthsocial="9" maxlength="11" />
  <input type="text" class="form-control maskval" autocomplete="off" maxlengthsocial="9" maxlength="9" />
</p>

my css

.maskNum {
  position: relative;
}

.maskval {
  position: absolute;
  top: 0;
  color: transparent !important;
  background: transparent !important;
  border: none;
  left: 0;
  text-indent: -9999px;
}

my jquery

var pattern = 'xxx-xx-0000'

$('.maskval').on('keyup keydown change', function() {
  var res = this.value,
    len = res.length,
    max = 9,
    stars = len > 0 ? len > 1 ? len > 2 ? len > 3 ? len > 4 ? 'XXX-XX-' : 'XXX-X' : 'XXX-' : 'XX' : 'X' : '',
    result = stars + res.substring(5),
    truckResult = result.substring(0, 11);
  $(this).prev('input').val(truckResult).trigger('change');
});

and a fiddle that I made to test what I've built so far. https://jsfiddle.net/5xwomLf7/8/

Upvotes: 3

Views: 111

Answers (1)

Hozeis
Hozeis

Reputation: 1742

If your patterns are only going to contain numbers and x´s:

var pattern = 'x0x-0x-00x0'
$('.maskval').on('keyup keydown change', function() {
    var input = $(this).val();
    var output = "";

    for (var x=0; x<input.length; x++){
        if (x < pattern.length){
            output = pattern[x]=='x' ? output + 'x' :  output + input[x];        
        } else
            output += input[x];  // or nothing if you want the value to be only as long as the pattern
    }  

    if (input.length < pattern.length && pattern[input.length] == '-') {
        output += '-';
        $(this).val(output);
    } else {
        $(this).prev('input').val(output);
    }
});

Upvotes: 3

Related Questions