Mascara Moeda - Money Mask

Atualizando (10-07-2020)

Achei esta função simples e facil de usar para quem quer gravar no SQL.
<script>
$(document).on('input','.valor',function(event) {
  if (this.value.length === 1) {this.value = '0'+this.value;}
  this.value = parseFloat(this.value.replace(/[^\d]/g,'').replace(/(\d\d?)$/,'.$1')).toFixed(2);
});
</script>

<input type="text" name="valor[]" class="valor" placeholder="0.00" autocomplete="off">


Temos a função jquery para fazer essa mascara:

Faça o download dos arquivos em http://plentz.github.io/jquery-maskmoney/

Para usar:
<script src="js/jquery-1.6.4.min.js"></script> <-- testei do 1.6.4 para cima
<script src="js/jquery.maskMoney.js" type="text/javascript"></script>

<input type=text name='valor' id='valor' size='10' />
<script type="text/javascript">$("#valor").maskMoney({thousands:'', decimal:'.'});</script>


E temos o abaixo também:

<script type='text/javascript'>
/* Autor: Mario Costa */
function formatar_moeda(campo, separador_milhar, separador_decimal, tecla) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? tecla.which : tecla.keyCode;

if (whichCode == 13) return true; // Tecla Enter
if (whichCode == 8) return true; // Tecla Delete
key = String.fromCharCode(whichCode); // Pegando o valor digitado
if (strCheck.indexOf(key) == -1) return false; // Valor inválido (não inteiro)
len = campo.value.length;
for(i = 0; i < len; i++) if ((campo.value.charAt(i) != '0') && (campo.value.charAt(i) != separador_decimal)) break; aux = ''; for(; i < len; i++) if (strCheck.indexOf(campo.value.charAt(i))!=-1) aux += campo.value.charAt(i); aux += key; len = aux.length; if (len == 0) campo.value = ''; if (len == 1) campo.value = '0'+ separador_decimal + '0' + aux; if (len == 2) campo.value = '0'+ separador_decimal + aux; if (len > 2) {
aux2 = '';

for (j = 0, i = len - 3; i >= 0; i--) {
if (j == 3) {
aux2 += separador_milhar;
j = 0;
}
aux2 += aux.charAt(i);
j++;
}

campo.value = '';
len2 = aux2.length;
for (i = len2 - 1; i >= 0; i--)
campo.value += aux2.charAt(i);
campo.value += separador_decimal + aux.substr(len - 2, len);
}

return false;
}

</script>

No html usar:

<input type=text name="valor" size=10 maxlength="10" onkeypress="return formatar_moeda(this,'','.',event);">

Comentários

  1. Fraguei meu nobre!
    Preciso de uma página htm e a função em php.
    O input obviamente seria colocado no body da html.
    E a function?

    ResponderExcluir
  2. Ola Rodi,

    No entusiasmo de colocar no ar, esqueci de colocar que esta em JavaSript, ja corrigi no script acima, pode usar agora, de preferencia antes do </head>

    ResponderExcluir

Postar um comentário

Postagens mais visitadas