How to add row in the footer that sum each column ?

How to add row in the footer that sum each column ?

ziv@kpmbro.comziv@kpmbro.com Posts: 73Questions: 28Answers: 4
edited September 2016 in General

Hi

I want to add a row in the <tfoot> , that sums up each column.

i try using the the sum plug, //cdn.datatables.net/plug-ins/1.10.12/api/sum().js.

but i got only one column sum, how can i target all columns beside one or two?

whats the best way of doing that ?

this is my table.

    var config_array = ({
      ServerSide: true,
      ajax: ({
        url: "view_stats/make_stats_test",
      data: {get_fields: params},
      type: 'POST',
      }),
      columns: columns,
      drawCallback:function(){var api = this.api();  $( api.table().footer() ).html(api.column( [4,5,6,7,8,9], {page:'current'} ).data().sum());},
      order: [
        [1, 'asc']
      ]
    });


    var table = $('#example').DataTable(config_array);

Thanks

This question has accepted answers - jump to:

Answers

  • allanallan Posts: 61,436Questions: 1Answers: 10,049 Site admin
    Answer ✓

    You'd need to loop over the columns updating each one. columns().every() can help with that.

    At the moment you are summing the values from all of those selected columns into a single value.

    Allan

  • allanallan Posts: 61,436Questions: 1Answers: 10,049 Site admin

    btw:

    ServerSide: true,

    There is no such option. Javascript is case sensitive. serverSide is used to enable server-side processing.

    Allan

  • ziv@kpmbro.comziv@kpmbro.com Posts: 73Questions: 28Answers: 4

    Thanks Allan,

    I try using the code in the example.
    after adding the sum class to the <th>.

    var table = $('#example').DataTable();
     
    table.columns( '.sum' ).every( function () {
        var sum = this
            .data()
            .reduce( function (a,b) {
                return a + b;
            } );
     
        $(el).html( 'Sum: '+sum );
    } );
    

    and i get this error:
    1026 Uncaught TypeError: Reduce of empty array with no initial value

    what did i missed?

    Thanks :)

  • ziv@kpmbro.comziv@kpmbro.com Posts: 73Questions: 28Answers: 4
    Answer ✓

    i got it, i find this code

            "footerCallback": function(row, data, start, end, display) {
              var api = this.api();
    
              api.columns('.sum', {
                page: 'current'
              }).every(function() {
                var sum = this
                  .data()
                  .reduce(function(a, b) {
                    var x = parseFloat(a) || 0;
                    var y = parseFloat(b) || 0;
                    return x + y;
                  }, 0);
                console.log(sum); //alert(sum);
                $(this.footer()).html(sum);
              });
            }
    

    its working now :)

    Thanks Allan

This discussion has been closed.