JSFiddle - React, Tailwind, and code Playground
HTML
<input id="amount"></>
JavaScript
$(document).on('keydown', '#amount', function(e){
var carattere = e.which;
var maxCifreParteIntera = 13;
var parteIntera = this.value.split(",")[0];
var parteDecimale = this.value.split(",")[1];
var inserimentoCifraDecimale = false;
var posizioneInserimento = this.selectionStart;
var posizioneVirgola = this.value.indexOf(",");
if(posizioneVirgola != -1 && posizioneInserimento > posizioneVirgola)
inserimentoCifraDecimale = true;
if(carattere == 8 && posizioneInserimento == posizioneVirgola+1) {
$(this).val(this.value.slice(0, posizioneVirgola+1));
return;
}
var res = parteIntera.match(/\./g);
var numeroSeparatoriMigliaia = 0;
if(res != null) {
numeroSeparatoriMigliaia = res.length;
var numeroCifreParteIntera = parteIntera.length - numeroSeparatoriMigliaia;
if(numeroCifreParteIntera >= maxCifreParteIntera && carattere != 188 && carattere != 8 && inserimentoCifraDecimale == false && carattere != 46) {
return;
}
}
if(this.selectionStart || this.selectionStart == 0){
// selectionStart won't work in IE < 9
var key = e.which;
var prevDefault = true;
var thouSep = "."; // your seperator for thousands
var deciSep = ","; // your seperator for decimals
var deciNumber = 2; // how many numbers after the comma
var thouReg = new RegExp("\\.","g");
var deciReg = new RegExp(deciSep,"g");
function spaceCaretPos(val, cPos){
/// get the right caret position without the spaces
if(cPos > 0 && val.substring((cPos-1),cPos) == thouSep)
cPos = cPos-1;
if(val.substring(0,cPos).indexOf(thouSep) >= 0){
cPos = cPos - val.substring(0,cPos).match(thouReg).length;
}
return cPos;
}
function spaceFormat(val, pos){
/// add spaces for thousands
if(val.indexOf(deciSep) >= 0){
var comPos = val.indexOf(deciSep);
var int = val.substring(0,comPos);
var dec = val.substring(comPos);
} else{
var int =...