Ki Lo
Ki Lo

Reputation: 41

javascript automatic format when fill input

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?

Upvotes: 0

Views: 132

Answers (1)

godismyjudge95
godismyjudge95

Reputation: 922

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

Upvotes: 1

Related Questions