JSFiddle - React, Tailwind, and code Playground
HTML
cost 1 :<input type="text" class="cost" name="cost1" /><br /> cost 2 :<input type="text" class="cost" name="cost2" /><br /> cost 3 :<input type="text" class="cost" name="cost3" /><br /> cost 4 :<input type="text" class="cost" name="cost4" /><br /><br
/> sum : <input type="text" id="sum" readonly />
JavaScript
$(document).ready(function() {
$(".cost").each(
function() {
$(this).keyup(
function() {
calculateSum()
});
});
});
function calculateSum() {
var sum = 0;
$(".cost").each(
function() {
var vl = this.value.replace(',', '');
if (!isNaN(vl) && vl.length != 0) {
sum += parseFloat(vl);
}
});
$("#sum").val(sum.toFixed(2));
}
$(document).ready(function() {
$('input.cost').keyup(function(event) {
// skip for arrow keys
if (event.which >= 37 && event.which <= 40) {
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g, "$1,").split("").reverse().join(""));
console.log(num2);
// the following line has been simplified. Revision history contains original.
$this.val(num2);
});
});
function RemoveRougeChar(convertString) {
if (convertString.substring(0, 1) == ",") {
return convertString.substring(1, convertString.length)
}
return convertString;
}