Icemanind
Icemanind

Reputation: 48696

Getting the total of a filtered field

I am using jQuery DataTables to create a table. I have a money field that I am summing and everything is working just fine, except for one issue. When I use the search filter, it is giving me a grand total of all rows. What I want is a grand total of just the rows returned by the filter. Here is my code:

var table = $('#tblAdvertising').DataTable({
    "iDisplayLength": 10,
    "bDestroy": true,
    "bLengthChange": false,
    "columnDefs": [
        { "visible": false, "targets": 0 }
    ],
    "drawCallback": function (settings) {
        var api = this.api();
        var rows = api.rows({ page: 'current' }).nodes();
        var last = null;

        api.column(0, { page: 'current' }).data().each(function (group, i) {
            if (last !== group) {
                $(rows).eq(i).before(
                    '<tr class="group"><td colspan="5">' + group + '</td></tr>'
                );

                last = group;
            }
        });
    },
    "footerCallback": function(row, data, start, end, display) {
        var api = this.api();

        var intVal = function(i) {
            return typeof i === 'string' ?
                i.replace(/[\$,]/g, '') * 1 :
                typeof i === 'number' ?
                i : 0;
        }

        var total = api.column(3).data().reduce(function(a, b) {
            return intVal(a) + intVal(b);
        });

        var pageTotal = api.column(3, { page: 'current' }).data().reduce(function (a, b) {
            return intVal(a) + intVal(b);
        });

        $(api.column(3).footer()).html('$' + pageTotal.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,') + '<hr style="margin: 0" />$' + total.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'));
    }
});

The issue is most likely in the line that starts with var total =. I am thinking I need to do something like var total = api.column(3).data().filteredData().... Of course that won't work, but any help would be appreciated!

Upvotes: 3

Views: 1965

Answers (1)

ZenCodr
ZenCodr

Reputation: 1175

In the last line, where you use column(3) also pass in {'search': 'applied'} (a selector-modifier) for the second argument.

var total = api.column(3, {'search': 'applied'}).data().reduce(function(a, b) {

Upvotes: 3

Related Questions