Filling in masked input with zeros

Asked

Viewed 232 times

0

I’m using the plugin https://igorescobar.github.io/jQuery-Mask-Plugin/ to create mask in an input field, the mask I am using is as follows:.

$('.campo').mask('0.0.00.000');

I need that when typing the numbers in my field the value related to mask is filled with 0 in it, ex:

1.0.23.000

In this example all initial input values are 0.0.00.000 and when typing the 0 would be filled by my value, if I removed the zero would reappear at that position.

Would anyone have any solution to this problem? The use of plugins is optional.

1 answer

1


Using Javascript only

String.prototype.reverse = function(){
  return this.split('').reverse().join(''); 
};

function mascara(campo,evento){
  var tecla = (!evento) ? window.event.keyCode : evento.which;
  var valor = campo.value.replace(/[^\d]+/gi,'').reverse();
  var resultado = "";
  var mascara = "#.#.##.###".reverse();
  for (var x=0, y=0; x<mascara.length && y<valor.length;) {
    if (mascara.charAt(x) != '#') {
      resultado += mascara.charAt(x);
      x++;
    } else {
      resultado += valor.charAt(y);
      y++;
      x++;
    }
  }
  campo.value = resultado.reverse();
}
<input type="Text" size="10" onKeyUp="mascara(this, event)"  value="">

  • I do not understand exactly what you want, if this example does not serve, please explain better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.