Issue
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.
Solution
Please see: Javascript Thousand Separator / string format
Consider the following.
$(function() {
function formatFloat(nStr) {
var result;
var dec = nStr.indexOf(".");
var x;
if (dec > 0) {
x = nStr.split(".");
x[0] = parseInt(x[0]);
} else {
x = [];
x.push(parseInt(nStr));
}
result = x[0].toLocaleString('en');
if (dec > 0) {
result = result + "." + x[1].slice(0,2);
}
return result;
}
$(".commas").keyup(function(e) {
e.preventDefault();
// Strip previous formatting
var v = $(this).val().split(",").join("");
// enter new formatting
$(this).val(formatFloat(v));
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Number: <input class="commas" type="text" /></p>
In this we split the string if there is a decimal .
point. We can use .toLocaleString("en")
to localize the number.
The toLocaleString() method returns a string with a language-sensitive representation of this number.
This does all the heavy comma lifting. We then add back the decimal value if needed.
Hope that helps.
Answered By - Twisty Answer Checked By - Gilberto Lyons (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.