Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm having issues with a tiny detail in inserting the sum value of each column, with class "sum", into its footer.

The code (more or less taken straight from DataTables.net) goes:

var table = $('#example').DataTable();
        table.columns('.sum').each(function (el) {
            var sum = table
                .column(el)
                .data()
                .reduce(function (a, b) {
                    return parseInt(a, 10) + parseInt(b, 10);
                });
            $(el).html('Sum: ' + sum);
        });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
628 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your table manipulation code needs to be executed only when DataTable is initialized, (see initComplete property).

Also make sure you have <tfoot></tfoot> block defined in your <table> otherwise there would be no footer.

Otherwise you were very close to the solution, please see below the corrected code:

var table = $('#ticketTable').DataTable({
    'initComplete': function (settings, json){
        this.api().columns('.sum').every(function(){
            var column = this;

            var sum = column
                .data()
                .reduce(function (a, b) { 
                   a = parseInt(a, 10);
                   if(isNaN(a)){ a = 0; }                   

                   b = parseInt(b, 10);
                   if(isNaN(b)){ b = 0; }

                   return a + b;
                });

            $(column.footer()).html('Sum: ' + sum);
        });
    }
});

See this JSFiddle for an example.

UPDATE

There is also footerCallback property that lets you defined footer display callback function which will be called on every "draw" event.

The difference between initComplete and footerCallback is that initComplete is called once and footerCallback on every "draw" event.

If you're displaying the sum for the whole table, initComplete should suffice. Otherwise if you require to show in the footer data relevant for current page only (as in Footer callback example), use footerCallback instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...