I'm trying to combine two Javascript functions into one code. The first function which targets the ".commas" class, inserts a comma after 3 digits. The second called "function floatKey" only allows one decimal point before the last two digits.
I tried inserting the ".commas" class function into the second one and removed the "event.preventDefault if statement", but the result was iffy - it allowed more digits after the decimal along with commas. It also removed all the commas before the decimal point. I also allowed "charCode 44" as an exception to the "if statement" in "function floatKey" but all it did was show and instantly disappear comma inserts. How would I combine these two functions to make both work?
My codes: ".commas" class function:
$(".commas").keyup(function(event){
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "");
var num2 = num.split(/(?=(?:\d{3})+$)/).join(",");
console.log(num2);
$this.val(num2);
});
function "floatKey":
function floatKey(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if(number.length>1 && charCode == 46){
return false;
}
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
I hope I explained my problem clear enough, thank you for your help.