0

JSFiddle for this question: http://jsfiddle.net/nhg5ej4s/

I use the 1.10.15 version of Datatables.

I have this sum() function registered in API:

 $.fn.dataTable.Api.register('sum()', function () {
     var data = this.flatten().toArray();
     return data.reduce(function (a, b) {
         return (a * 1) + (b * 1); // cast strings
     }, 0);
 });

When I need to use this function, for example, in drawCallback option for update totals in footer (see JSFiddle for context):

var table = $('#example').DataTable({
    drawCallback: function (settings) {
       var api = this.api();
       $(api.column(5).footer()).html('Total: ' + api.column(5).data().sum());
    }
});

The function works, but when I apply filter on the table with any search, the values passed to sum() take all rows, not that filtered by search.

There is a way to identify the search context inside the sum() function?

PS: While writing this questions, I realize that I can pass a option in column call that will filter only searched rows: api().column(5, {'search': 'applied'}).data().sum() but I decide to keep the question to know if there is a way to do this inside the sum() code. JSFidlle with this update

2
  • 1
    Honestly, the 'search' : 'applied' is your best bet, especially if you get into pagination. You can look at this for other ideas though if you really want to add something in your sum() function: stackoverflow.com/questions/12915988/… Commented Jun 16, 2017 at 15:37
  • I agree with you @Woodrow. If you want to put this as an answer... Commented Jun 16, 2017 at 16:40

1 Answer 1

1

Honestly, the 'search' : 'applied' is your best bet, especially if you get into pagination. You can look at this for other ideas though if you really want to add something in your sum() function: Retrieving row data after filtering JQuery Datatables

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.