Account Plan Mask in javascript

Asked

Viewed 277 times

2

How can I do a javascript function to format the values typed in an input to the default account plan similar to the one below.

1 (min)
1.1
1.1.1
1.1.1.01
1.1.1.01.001 (max)

Column Bill

inserir a descrição da imagem aqui

1 answer

3


You can use the low function which checks the 8 digits and applies the points "." according to the standard.

You need to put onkeyup="mascara(this)" in the field you want to mask to call the function.

Behold:

function mascara(i){
   var v = i.value;
   
   // este "if" impede que sejam inseridos
   // outros caracteres que não sejam números
   if(isNaN(v[v.length-1])){
      i.value = v.substring(0, v.length-1);
      return;
   }

   v = i.value.replace(/\./g,"");

   i.value = v[0]
   + (v[1] ? "."+v[1] : '')
   + (v[2] ? "."+v[2] : '')
   + (v[3] ? "."+v[3] : '')
   + (v[4] || '')
   + (v[5] ? "."+v[5] : '')
   + (v[6] || '')
   + (v[7] || '');
}

// Breve explicação:
// v[x] onde "x" é a posição do caractere na string.
// Ex.: v = "foo", logo v[0] = "f", v[1] e v[2] = "o"

// Operadores:
// (v[1] ? "."+v[1] : '')
// Se v[1] for true (existe), retorna "."+v[1];
// senão, retorna '' (vazio)

// (v[4] || '')
// se v[4] for true (existe), retorna ele mesmo,
// senão retorna '' (vazio)
<input maxlength="12" type="text" id="numero" onkeyup="mascara(this)" />

  • Thanks friend was what I needed, but kindly, could you explain these two lines of code to me to get the logic? (v[3] "."+ v[3] ') + (v[4] || '')

  • I put an explanation in the code. Abs!

Browser other questions tagged

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