0

I have used a input like that:

<input type="text" onkeypress="maskDexxtz(this,maskCPF)" maxlength='14'  title="<?php echo $this->__('Tax/VAT number') ?>"/>

I want to format input when customer type as: xxx.xxx.xxx-xx My js code:

<script type="text/javascript">
    function maskCPF(v) {
    v = v.replace(/\D/g, "");
    v = v.replace(/(\d{3})|(\.{1}d{3})/g, "$1.$2");
    return v;
}

function maskDexxtz(o, f) {
    v_obj = o
    v_fun = f
    setTimeout('mask()', 1)
}

function mask() {
    v_obj.value = v_fun(v_obj.value)
}
</script>

However I just make it as xxx.xxx.xxx but can't capture two last key -xx. Anywho can help me for it?

Ki Lo
  • 41
  • 7
  • Possible duplicate of [Format a phone number as a user types using pure JavaScript](https://stackoverflow.com/questions/30058927/format-a-phone-number-as-a-user-types-using-pure-javascript) – 31piy Apr 09 '18 at 17:21
  • oh no, it is phone. However, I use include text, number in this field so it isn't duplicate – Ki Lo Apr 09 '18 at 17:59

1 Answers1

1

Here is a working version. I don't think there is a way to do this with regex replace.

$('input').on('keypress', (e, el) => {
    mask(e.currentTarget);
})

function mask(el) {
  timeout = setTimeout(() => {
    el.value = el.value.replace(/\D/g, "");
    let parts = el.value.match(/(\d{1,3})?(\d{1,3})?(\d{1,3})?(\d{1,2})?/);
    el.value = '';
    for(let i = 1; i <= 4; i++) {
      if(parts[i] !== undefined) {
      el.value += parts[i];
        if(parts[i+1] !== undefined) {
        el.value += i < 3 ? '.' : '';
        el.value += i == 3 ? '-' : '';
        }
      }
    }
  }, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" onkeypress="" maxlength='14'  title="Tax/VAT number"/>
godismyjudge95
  • 922
  • 1
  • 9
  • 15