2016-10-14 21 views
1

鑑於此footer_callback數據表示例 這裏是我的FIDDLE使用footer_callback求和數據表頁腳中的1+列?

這基本上總計每欄的總數爲1列。 任何人都可以建議我怎麼能做到這一點超過1列?

我想我可能需要增加更多的th標籤我要總結的列:

<tfoot> 
     <tr> 
      <th colspan="4" style="text-align:right">Total:</th> 
      <th></th> 
     </tr> 
    </tfoot> 

以及每個列添加另一個回調函數,但到目前爲止,我還沒有喜悅。 任何人都可以建議嗎?

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

     // Remove the formatting to get integer data for summation 
     var intVal = function (i) { 
      return typeof i === 'string' ? 
       i.replace(/[\$,]/g, '')*1 : 
       typeof i === 'number' ? 
        i : 0; 
     }; 

     // Total over all pages 
     total = api 
      .column(4) 
      .data() 
      .reduce(function (a, b) { 
       return intVal(a) + intVal(b); 
      }, 0); 

     // Total over this page 
     pageTotal = api 
      .column(4, { page: 'current'}) 
      .data() 
      .reduce(function (a, b) { 
       return intVal(a) + intVal(b); 
      }, 0); 

     // Update footer 
     $(api.column(4).footer()).html(
      '$'+pageTotal +' ($'+ total +' total)' 
     ); 
    } 

注:我可能需要與我可以總結上號碼錶/數據集的另一列。
更改了表格,因此有2列可以求和FIDDLE在這個小提琴中,它正在第5欄中工作,但是如何讓它在第3欄中工作?

+0

重複'//總共覆蓋所有頁面,'//總共覆蓋此頁面',//更新頁腳3的步驟也是索引3。 –

+0

@SanthoshNayak我已經嘗試過,但可以提供一個例子,tks? – HattrickNZ

回答

3

查看fiddle here。我正在使用sum plugin。通過這種方法,您可以將列索引添加到數組中以對其進行總計。

我還添加了「應用」過濾器,以便在過濾時總計動態更新。

$(document).ready(function() { 

     // SUM PLUGIN 
     jQuery.fn.dataTable.Api.register('sum()', function () { 
      return this.flatten().reduce(function (a, b) { 
       if (typeof a === 'string') { 
        a = a.replace(/[^\d.-]/g, '') * 1; 
       } 
       if (typeof b === 'string') { 
        b = b.replace(/[^\d.-]/g, '') * 1; 
       } 

       return a + b; 
      }, 0); 
     }); 

     $('#example').DataTable({ 
      "footerCallback": function() { 
       var api = this.api(), 
        columns = [3, 5]; // Add columns here 

       for (var i = 0; i < columns.length; i++) { 
        $('tfoot th').eq(columns[i]).html('Total: ' + api.column(columns[i], {filter: 'applied'}).data().sum() + '<br>'); 
        $('tfoot th').eq(columns[i]).append('Page: ' + api.column(columns[i], { filter: 'applied', page: 'current' }).data().sum()); 
       } 
      } 
     }); 
    }); 
相關問題