Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save iamrealfarhanbd/560178729e08362fcad5427e50264e1c to your computer and use it in GitHub Desktop.
Save iamrealfarhanbd/560178729e08362fcad5427e50264e1c to your computer and use it in GitHub Desktop.
This JavaScript code snippet enhances Ninja Tables by providing advanced calculation capabilities. It calculates the sum of specified columns, taking into account decimal separators in cell values. The code ensures that the total result is rendered correctly with a decimal separator if cell values have decimal places, while rendering as a regula…
const myClasses = "column_one, column_two, column_three";
const totalText = "Total: ";
if (!$table.find('tfoot').length) {
$("<tfoot></tfoot>").appendTo($table);
}
const getSum = classes => {
let sum = 0;
let index = 0;
$table.find(`.${classes}`).each(function() {
const val = $.trim($(this).text());
if (val) {
const numVal = parseFloat(val.replace(/,/g, ""));
sum += !isNaN(numVal) ? numVal : 0;
}
});
index += jQuery(`.${classes}`).index() + 1;
return [sum, index];
};
getSum();
const renderTfoot = () => {
const counts = $table.find(".footable-header th").length;
const num = parseInt(counts);
const notThis = jQuery('.footable-header th')
.filter((index, element) => jQuery(element).css('display') == 'none')
.map((index, element) => parseInt(jQuery(element).index(), 10) + 1)
.toArray();
const container = $("<tr class='final_result' />");
for (let i = 1; i <= num; i++) {
if (!notThis.includes(i)) {
$('<td />', {
id: `id${i}`,
name: `name${i}`
}).appendTo(container);
}
}
$('tfoot').prepend(container);
};
const responisveChanges = singleClass => {
const isVisible = jQuery(`th.${singleClass}`).css('display') !== 'none';
const childSelector = `tfoot .final_result td:nth-child(${getSum(singleClass)[1]})`;
$table.find(`${childSelector}`).toggle(isVisible);
};
const setSumAmount = () => {
const substr = myClasses.split(',');
substr.forEach(val => {
const singleClass = `ninja_clmn_nm_${val.trim()}`;
const sum = getSum(singleClass)[0];
let formattedSum = sum.toLocaleString();
if (sum % 1 !== 0) {
formattedSum = sum.toFixed(2).toLocaleString();
}
const totalHtml = `${totalText} ${formattedSum}`;
const childSelector = `tfoot .final_result td#id${getSum(singleClass)[1]}`;
$table.find(`${childSelector}`).html(totalHtml);
responisveChanges(singleClass);
jQuery(window).on('resize', () => {
responisveChanges(singleClass);
});
});
};
const setSumOnEvent = () => {
setSumAmount();
$table.on('after.ft.filtering', setSumAmount);
$table.on('after.ft.paging', setSumAmount);
};
renderTfoot();
setSumOnEvent();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment