How to sum a filtered html table?

╄→尐↘猪︶ㄣ 提交于 2020-07-15 09:47:26

问题


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 displayed in the "total" row should be the sum of all rows displayed, i.e. not take account of the hidden rows.

I tried to add a condition like to make the summing dependent on the display style of the row, however that didn't work out. Is there any simple solution to implement this? Like a simple javascript if condition that checks if the row the td element is a part of is hidden or not?

EDIT: My HTML-Coods looks like this (javascript function that calculates the column total comes after the table):

var columnCount = document.getElementById('datatable').rows[2].cells.length;
var tds = document.getElementById('datatable').getElementsByTagName('td');
var sum = 0;

var columnsToSum = [3,4];

for (i=0; i<columnsToSum.length;i++) 
{
    a = columnsToSum[i]; 
    sum=0;
    var hasPercent = false;
    
    for(z = columnsToSum[i]; z < tds.length; z+=columnCount) 
    {
        sum += isNaN(tds[z].innerHTML) ? 0 : parseInt(tds[z].innerHTML); 
    }

    document.getElementById("data"+ a).innerHTML = sum;                             
}
<html>
    <head>
        <meta charset="utf-8"/>
 
         <link rel="stylesheet" href="css2/bootstrap.css" />
         <link rel="stylesheet" href="css2/dataTables.bootstrap.min.css" />
         <link rel="stylesheet" href="css2/responsive.bootstrap.min.css" type="text/css" />
         <link rel="stylesheet" href="css2/buttons.bootstrap.min.css" type="text/css" />
         <link rel="stylesheet" href="style.css" />
      </head>
    <body>
        <div class="container-fluid" style="width:80%;">
            <table id=datatable class="datatable table table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Address</th>
                        <th>Class</th>
                        <th>Class</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th>
                            <input type="text" class="form-control input-sm filter-column" placeholder="nach ID filtern"> 
                        </th>
                        <th>
                            <input type="text" class="form-control input-sm filter-column"> 
                        </th>
                        <th>
                            <input type="text" class="form-control input-sm filter-column" />
                        </th>
                        <th>
                            <select class="form-control input-sm filter-column">
                                <option value="A">A</option>
                                <option value="B">B</option>
                                <option value="B">C</option>
                            </select>
                        </th>
                        <th>
                            <select class="form-control input-sm filter-column">
                                <option value="A">A</option>
                                <option value="B">B</option>
                                <option value="B">C</option>
                            </select>
                        </th>
                    </tr>
                </tfoot>
            <tbody> 
                <tr>
                    <td>1</td> 
                    <td>bla</td> 
                    <td>500</td> 
                    <td>100%</td> 
                    <td>300</td> 
                </tr> 
            </tbody>
            <tfoot>
                <tr class="sum-row">
                    <td id=data0></td> 
                    <td id=data1></td> 
                    <td id="data2">0</td> 
                    <td id="data3">0</td>
                    <td id="data4">0</td> 
                </tr> 
            </tfoot>
        </table>   
    </div> 
    <script language="javascript" type="text/javascript">
    
    </script>
    <script src="js2/jquery-1.11.3.min.js"></script>
    <script src="js2/jquery.dataTables.min.js"></script>
    <script src="js2/dataTables.bootstrap.min.js"></script>
    <!-- Responsive extension -->
    <script src="js2/responsive.bootstrap.min.js"></script>
    <!-- Buttons extension -->
    <script src="js2/dataTables.buttons.min.js"></script>
    <script src="js2/buttons.bootstrap.min.js"></script>
    <script src="js2/jszip.min.js"></script>
    <script src="js2/buttons.html5.min.js"></script>

The code above always shows the total sum of all values in the table and doesn't take account of the filtering.


回答1:


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;
    }
}



回答2:


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()


来源:https://stackoverflow.com/questions/56878589/how-to-sum-a-filtered-html-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!