数据表根据另一个值计算列总数

时间:2019-03-28 15:35:42

标签: javascript jquery datatable datepicker

使用数据表1.10.19

我的表中有五列,column 2包含价格,column 5包含字符串。我想计算第2列的总计,其中第5列等于“现金”

我还想根据日期范围执行计算。我该如何实现?

我已经尝试了以下方法,但是它并没有按照我的意愿工作。它可以成功地计算总数,但不会基于任何过滤器。它只是将所有列2中的值相加。

$('.date-range-filter').change(function() {

    // get all values in column 2
    var cashTotalData = api.search('Cash').column(2, {
        page: 'all'
    }).data();

    // calculate all values
    var cashTotalValue = cashTotalData.reduce(function(a, b) {
        return intVal(a) + intVal(b);
    }, 0).toFixed(2);

    console.log(cashTotalValue); // this displays the correct total of *all* values in column 2, but not the total based on my date range

    $('#records').DataTable().draw();
});

任何建议都值得赞赏。

1 个答案:

答案 0 :(得分:-1)

我不认为您想要.search(),我认为您想要.filter(),但是我不知道该怎么做。我在下面提供的示例仅循环浏览行并总计美元金额。

$(document).ready(function(){
    var table = $("#table").DataTable();
    $('.date-range-filter').click(function() {
        let cashTotalValue = 0;

        table.rows().eq(0).each(function(index){
            var row = table.row( index );
            console.log(row.data());
            // the "type" column is #5, but arrays are 0 based, so subtract one
            if (row.data()[4] == 'Cash') {
                // the "amount" column is #2, but arrays are 0 based, so subtract one
                cashTotalValue += parseInt(row.data()[1]);
            }
        });

        console.log(cashTotalValue.toFixed(2)); // this displays the correct total of *all* values in column 2, but not the total based on my date range
        alert(cashTotalValue.toFixed(2)); // this displays the correct total of *all* values in    
    });
});
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="table">
    <thead>
        <tr>
            <th>Transaction</th>
            <th>Amount</th>
            <th>Description</th>
            <th>Date</th>
            <th>Type</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>3</td>
            <td>Description</td>
            <td>11/15/2018</td>
            <td>Cash</td>
        </tr>
        <tr>
            <td>2</td>
            <td>5</td>
            <td>Description</td>
            <td>11/15/2018</td>
            <td>Credit</td>
        </tr>
        <tr>
            <td>3</td>
            <td>7</td>
            <td>Description</td>
            <td>11/16/2018</td>
            <td>Cash</td>
        </tr>
        <tr>
            <td>4</td>
            <td>11</td>
            <td>Description</td>
            <td>11/16/2018</td>
            <td>Credit</td>
        </tr>
    </tbody>
</table>
<input type="button" class="date-range-filter" value="Click"/>