How to sum a filtered html table?

前端 未结 2 1994
一个人的身影
一个人的身影 2021-01-17 05:22

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

相关标签:
2条回答
  • 2021-01-17 05:34

    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:

    1. Array.from()
    2. Array.prototype.filter()
    3. Array.prototype.reduce()
    0 讨论(0)
  • 2021-01-17 05:49

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题