Created
June 27, 2017 13:00
-
-
Save maxcelos/a33bfe30c367dd20749cf29a5fe14e14 to your computer and use it in GitHub Desktop.
Monetary JQuery mask
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Working example: https://fiddle.jshell.net/marcelobdsilva/s11pvckm/