JSFiddle - React, Tailwind, and code Playground
math functions
by khemikal
JavaScript
//add commas
function addCommas(y,z) {
$(y).each(function () {
var t = $(this).html();
t = t.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
if (z.toString() == 'no') {
$(this).html(t.toLocaleString("en"))
}
else {
$(this).html(t.toLocaleString("en").split('.')[0])
}
});
}
//grand total function
function calcSum(a, b) {
var sum = 0;
// iterate through each td based on class and add the values
$(a).each(function () {
var theVal = $(this).text();
// add only if the value is number
if (!isNaN(theVal) && theVal.length != 0) {
sum += parseFloat(theVal);
}
});
$(b).text(sum);
};
//percents
function thePercentages(x,y,z) {
var test0 = parseInt($(x).text());
var test1 = parseInt($(y).text());
var sum = parseFloat(((test0 - test1) / test1) * 100).toFixed(2);
$(z).html(sum);
}
//v is parent,z is child element,w is which child column....ex: 0 or 1, y is first run or not, z is class name you want assigned
function subtotals(v, w, x, y, z) {
$(v).each(function (index, element) {
var subTotalAmt = 0;
var numRows = parseInt($(this).attr("rowspan"));
var firstRow = $(this).parent();
var lastRow = firstRow.nextAll('tr').slice(numRows - 2, numRows - 1);
var currentRow = firstRow;
for (i = 0; i < numRows; i++) {
var tdValue = 0;
if (!isNaN(parseInt($(currentRow.children(w)[x]).text()))) {
tdValue = parseInt($(currentRow.children(w)[x]).text());
}
subTotalAmt += tdValue;
currentRow = currentRow.next("tr");
}
if (y == 'yes') {
lastRow.after('<tr><td class="sub0">Sub Total</td><td class="' + z + '">' + subTotalAmt + '</td></tr>');
$(this).attr('rowspan', numRows + 1);
}
else {
lastRow.append('<td class="' + z + '">' + subTotalAmt +...