I have a HTML Table that I am able to filter with jquery. At the bottom of my table, i want to have a "total" row, that sums all values displayed. The sum displaye
You can query the DOM and filter by attr as follows:
Array
.from(document.querySelectorAll('table#datatable td')) // Or some other selector you wish
.filter(r=>r.hidden) // Enter here your filter func. Can also filter by `r.style.display` etc.
.reduce((sum, curr)=>sum+(Number(curr.innerHTML) || 0), 0) // Here we try to get the value of the td. If it will resolve to NaN ==> We will return 0 and won't affect the value.
This will yield the sum you desire. Place that value wherever you want then :)
Resources:
I think this code will work.
$(document).ready(function () {
var table = $('#datatable').DataTable();
calculatesum(table.rows().nodes());
$('input').on('keyup click', function () {
var searched = table.rows({
search: 'applied'
}).nodes();
calculatesum(searched);
});
});
function calculatesum(all) {
var columnsToSum = [2, 4];
for (i = 0; i < columnsToSum.length; i++) {
a = columnsToSum[i];
sum = 0;
for (j = 0; j < all.length; j++) {
var val = all[j].getElementsByTagName('td')[a].innerHTML;
sum += isNaN(val) ? 0 : parseInt(val);
}
document.getElementById("data" + a).innerHTML = sum;
}
}