Filling input masked with zeros

0

I'm using the link plugin to create mascara in an input field, the mask I'm using is the next.

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

I need that when entering the numbers in my field the value referring to the mask be filled with 0 in the same, eg:

1.0.23.000

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

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

    
asked by anonymous 05.07.2016 / 15:50

1 answer

1

Using only JavaScript

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="">
    
19.11.2016 / 02:23