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?

2

1 Answer 1

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"/>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.