Insert comma automatically while typing

Asked

Viewed 1,899 times

0

When typing a value, there is some way to already make the correction by inserting commas and live points??

EX: I pressed 4 + 3 + 6 on the keyboard Input ja Mosta = 4,36

EX: I pressed 4 + 3 + 6 + 8 + 8 + 8 on the keyboard Input ja Mosta = 4.368.88

I managed to do using the jquery Mask plugin, but I wonder if it is possible using jquery, without plugins.

$( '#preco' ).keyup( function() {
   $('#preco').mask("#.###,##", {reverse: true});
});

4 answers

1

I always use this little function that I will leave here in the reply. It dispenses with the use of plugins and is done with a simple jQuery.

Serves for CPF, CNPJ and other various types of formatting you want. You can even create your own formatting according to your need. Just like I did with "STATE REGISTRATION" when I needed it.

//Essa função é para verificar se o valor passado pelo input é String. Se for String não é aceito (é apagado)
function MascaraInteiro(num) {
  var er = /[^0-9/ ().-]/;
  er.lastIndex = 0;
  var campo = num;
  if (er.test(campo.value)) { ///verifica se é string, caso seja então apaga
    var texto = $(campo).val();
    $(campo).val(texto.substring(0, texto.length - 1));
    return false;
  } else {
    return true;
  }
}

//Formata de forma generica os campos (Essa é a função que realmente formata os campos, com a exceção do campo de MOEDA)
function formataCampo(campo, Mascara) {
  var boleanoMascara;

  var exp = /\-|\.|\/|\(|\)| /g
  var campoSoNumeros = campo.value.toString().replace(exp, "");
  var posicaoCampo = 0;
  var NovoValorCampo = "";
  var TamanhoMascara = campoSoNumeros.length;
  for (var i = 0; i <= TamanhoMascara; i++) {
    boleanoMascara = ((Mascara.charAt(i) == "-") || (Mascara.charAt(i) == ".") ||
      (Mascara.charAt(i) == "/"))
    boleanoMascara = boleanoMascara || ((Mascara.charAt(i) == "(") ||
      (Mascara.charAt(i) == ")") || (Mascara.charAt(i) == " "))
    if (boleanoMascara) {
      NovoValorCampo += Mascara.charAt(i);
      TamanhoMascara++;
    } else {
      NovoValorCampo += campoSoNumeros.charAt(posicaoCampo);
      posicaoCampo++;
    }
  }
  campo.value = NovoValorCampo;
  ////LIMITAR TAMANHO DE CARACTERES NO CAMPO DE ACORDO COM A MASCARA//
  if (campo.value.length > Mascara.length) {
    var texto = $(campo).val();
    $(campo).val(texto.substring(0, texto.length - 1));
  }
  //////////////
  return true;
}

//Essa função é para o caso da formatação ser em MOEDA. Entao você deverá chamá-la no INPUT.
function MascaraMoeda(i) {
  var v = i.value.replace(/\D/g, '');
  v = (v / 100).toFixed(2) + '';
  v = v.replace(".", ",");
  v = v.replace(/(\d)(\d{3})(\d{3}),/g, "$1.$2.$3,");
  v = v.replace(/(\d)(\d{3}),/g, "$1.$2,");
  i.value = v;

}

//O segundo parâmetro desta função, é o nome que você coloca lá na chamada dela no INPUT. Isso determina em qual condicional (if, else if, else) a função entrará e qual formatação ela executará.
function MascaraGenerica(seletor, tipoMascara) {
  setTimeout(function() {
    if (MascaraInteiro(seletor)) {
      if (tipoMascara == 'CPFCNPJ') {
        if (seletor.value.length <= 14) { //cpf
          formataCampo(seletor, '000.000.000-00');
        } else { //cnpj
          formataCampo(seletor, '00.000.000/0000-00');
        }
      } else if (tipoMascara == 'DATA') {
        formataCampo(seletor, '00/00/0000');
      } else if (tipoMascara == 'CEP') {
        formataCampo(seletor, '00.000-000');
      } else if (tipoMascara == 'TELEFONE') {
        formataCampo(seletor, '(00) 0000-0000');
      } else if (tipoMascara == 'CELULAR') {
        formataCampo(seletor, '(00) 00000-0000');
      } else if (tipoMascara == 'INTEIRO') {
        formataCampo(seletor, '00000000000');
      } else if (tipoMascara == 'CPF') {
        formataCampo(seletor, '000.000.000-00');
      } else if (tipoMascara == 'CNPJ') {
        formataCampo(seletor, '00.000.000/0000-00');
      } else if (tipoMascara == 'INSCRICAOESTADUAL') {
        formataCampo(seletor, '00.000.00-0');
      }
    }
  }, 200);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label><b>CNPJ:</b> </label>
<input onKeyPress="MascaraGenerica(this, 'CNPJ');" type="text">
<br><br>

<label><b>CPF:</b> </label>
<input onKeyPress="MascaraGenerica(this, 'CPF');" type="text">
<br><br>

<label><b>CEP:</b> </label>
<input onKeyPress="MascaraGenerica(this, 'CEP');" type="text">
<br><br>

<label style="color:green"><b>MOEDA:</b> </label>
<input onKeyPress="MascaraMoeda(this);" type="text">
<br><br>

<label><b>CELULAR:</b> </label>
<input onKeyPress="MascaraGenerica(this, 'CELULAR');" type="text">
<br><br>

<label><b>TELEFONE:</b> </label>
<input onKeyPress="MascaraGenerica(this, 'TELEFONE');" type="text">
<br><br>

<label><b>INSCRIÇAÕ ESTADUAL:</b> </label>
<input onKeyPress="MascaraGenerica(this, 'INSCRICAOESTADUAL');" type="text">
<br><br>

Event keypress -> The event keypress is triggered when a key that produces a character type value is pressed.

The answer code could have been much smaller if I answered only the question raised in the question. But I preferred to leave the most complete and comprehensive answer.

Follow the link for future consultation: Github

As soon as I find the site where I found this function, I promise to reference here.

I hope it helps!

0

You can use Jquery.Mask and pass the format you want, example:

$('.classeNoInput').mask("#.##0,00", {reverse: true});

Follows the documentation link

This solution serves other formats as well as date, zip code, phone etc.

  • the live part doesn’t work using it $( '#price' ).keyup( Function() { $('#price'). Mask("#. ###,##", {Reverse: true}); });

  • no need to use keyup, it does automatically, just need to apply the mask in the input

0

**Use the library

jquery and jquery.maskMoney.min.js

**

In your script you get : **

$("#valorPrimeiroPedido").maskMoney({
        prefix: "R$:",
        decimal: ",",
        thousands: "."
    });

in Html

<input class="form-control" type="text" id="valorPrimeiroPedido"  />

0

Arson speaks, all beauty? (:

Dude, I don’t know how I would do with jQuery, but in pure Javascript from the Ecmascript 6 has a specific feature to make this conversion, and it has some nice attributes. Follow the example:

First I declare a variable, which will receive the value in cash (in our example, 1,000.00).

var din = 1000;

After that, I will invoke the functionality that will perform this conversion, passing our variable declared above by parameter:

new Intl.NumberFormat('pt-BR',
  { style: 'currency', currency: 'BRL' }
).format(din); // "R$ 1.000,00"

Ready! The function will return the formatted value and converted into Real. (:

You can change the attributes to convert to other currencies around the world. And it’s okay to use it with your jQuery code, after all, it’s all Javascript. xd

If you want to know a little more about, I’ll leave here the link of the article I read talking about, follows: https://www.samanthaming.com/tidbits/30-how-to-format-currency-in-es6/

I hope I helped, hugging!

Browser other questions tagged

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