Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
642 views
in Technique[技术] by (71.8m points)

javascript - DataTables.net table column sum in footer

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...