In this tutorial we will learn to calculate the sum of input numbers on a webpage separated by comma using JavaScript.
Usually the sum of input numbers is carried out by using a JavaScript function. Think of formatting the input numbers separated by comma before calculating the sum and obtaining the formatted output. i.e., formatting the input numbers first and then calculating sum of the formatted input numbers.
Let's try this out.
We need to write two JavaScript functions:
//Using this script, the input numbers will be formatted. $('.number').keyup(function(event) { // skip for arrow keys if (event.which >= 37 && event.which <= 40) { event.preventDefault(); } $(this).val(function(index, value) { value = value.replace(/,/g, ''); return numberWithCommas(value); }); }); //Replace numbers with comma separated numbers. function numberWithCommas(x) { var parts = x.toString().split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); return parts.join("."); }
//Calculate the sum of two input integers. function Calculate() { var a, b; a = parseFloat(document.getElementById("input1").value.replace(/,/g, "")); if (isNaN(a) == true) { a = 0; } var b = parseFloat(document.getElementById("input2").value.replace(/,/g, "")); if (isNaN(b) == true) { b = 0; } document.getElementById("totalSpan").innerHTML = numberWithCommas(parseFloat(a + b).toFixed(2)); }