Wednesday, February 20, 2013

Add Total Row in jQuery DataTables

1) json response written by spring mvc 3


      @RequestMapping(value = "/getTestData", produces = "application/json")
public @ResponseBody List<TestData> getTestDataTable() {

List<TestData> result = new ArrayList<TestData>();
TestData d1 = new TestData();
d1.setName("Hello A");
d1.setNuma(1100);
d1.setNumb(7);

TestData d2 = new TestData();
d2.setName("B hello");
d2.setNuma(3412);
d2.setNumb(5);
result.add(d1);
result.add(d2);

return result;
}


This is the response sample:

[{"name":"Hello A","numa":1100,"numb":7},{"name":"B hello","numa":3412,"numb":5}]


2) add a table in html


<table id="id_dt_test" class="display">
<thead>
<tr>
<th width="20%">Name</th>
<th width="20%">Number A</th>
<th width="20%">Number B</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th style="text-align: right">Total:</th>
<th style="text-align: left"></th>
<th style="text-align: left"></th>
</tr>
</tfoot>
</table>

3)  init datatables


$('#id_dt_test').dataTable({
"bProcessing" : true,
"bDestroy" : true,
"sAjaxSource" : 'getTestData.do',
"sAjaxDataProp" : "",
"bFilter" : false,
"bInfo" : false,
"bLengthChange" : false,
"aoColumns" : [ {
"mData" : "name"
}, {
"mData" : "numa",
}, {
"mData" : "numb"
} ],
"bPaginate" : false,
"bAutoWidth" : false,
"fnFooterCallback" : function(nRow, aaData, iStart, iEnd,
aiDisplay) {
var iTotalNuma = 0;
var iTotalNumb = 0;
if (aaData.length > 0) {
for ( var i = 0; i < aaData.length; i++) {
iTotalNuma += aaData[i].numa;
iTotalNumb += aaData[i].numb;
}
}
/*
* render the total row in table footer
*/
var nCells = nRow.getElementsByTagName('th');
nCells[1].innerHTML = iTotalNuma;
nCells[2].innerHTML = iTotalNumb;

}
});



4) actual result:




Reference URL:
http://datatables.net/release-datatables/examples/advanced_init/footer_callback.html

1 comment:

  1. nice info..
    i have tied it.
    but why the result is NaN??
    it works only sum a coloum like your reference.
    i have to sum 3 coloums.
    how can it works?

    thanks lot.

    ReplyDelete