Skip to content

Instantly share code, notes, and snippets.

@maxcelos
Created June 27, 2017 13:00
Show Gist options
  • Save maxcelos/a33bfe30c367dd20749cf29a5fe14e14 to your computer and use it in GitHub Desktop.
Save maxcelos/a33bfe30c367dd20749cf29a5fe14e14 to your computer and use it in GitHub Desktop.
Monetary JQuery mask
// To use it, jus add the "money" class on your input field
$('.money').on('keypress', function (e) {
// Accept only numbers
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
}).on('keyup', function (e) {
var v = $(this).val().replace(/\D/g,"");
if(v == ''){
$(this).val('0,00')
}else{
var newV = '';
v = parseInt(v).toString();
if(v.length < 3){
for (var i = 0; i < 3 - v.length; i++){
newV = '0'+newV;
}
}
newV = newV+v;
newV = newV.split('');
var sNewv = '';
var mil = 0;
for(var i = newV.length - 1; i >= 0 ; i--){
sNewv = newV[i] + sNewv;
mil++;
if(sNewv.length == 2){
sNewv = ',' + sNewv;
mil = 0;
}
if(mil == 3 && i > 0){
sNewv = '.' + sNewv;
mil = 0;
}
}
$(this).val(sNewv);
}
});
@maxcelos
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment