I have used a datatable in my codeigniter application to dynamically print database values. I am trying to sum up all the columns including numeric and string values. The numeric values are correct but the string column sum is weirdly wrong. The sum only works for some of the values of the column. For example it sums up 8 out of 10 rows. But the numeric sum shows sum of all 10 rows. I am providing the code below. Note: I am trying to use the headercallback() to print the sums of the columns. I have used two headers for this.
Datatable HTML code:
<table id="tabular" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Company</th>
<th>Status</th>
<th>Created Date</th>
<th>Total Contacts</th>
<th>Total Versions</th>
<th>Articles Assigned</th>
</tr>
</thead>
<thead id="totals">
<tr>
<th id="name">asdfasf</th>
<th></th>
<th></th>
<th id="contact"></th>
<th id="version"></th>
<th id="article"></th>
</tr>
</thead>
<tbody>......(Rest of the code)
JS code to initialize the datatable on the given HTML
$(document).ready(function() {
var oTable = $('#tabular').DataTable({
// "stateSave": true,
// "order": [],
"dom": '<"row search-padding" <"col-md-12 search-padding" <"col-md-6 search-padding pull-left" <"#inp">> <"col-md-6 search-padding" <"datatable-n pull-right" l >> > >rt <"row" <"col-md-6" i > <"col-md-6" p > >',
"columns" : [
{"width": "25%" },
{"width": "18.7%" },
{"width": "18.7%" },
{"width": "14%" },
{"width": "10.7%" },
{"width": "18.7%" },
],
"stashSave":true,
"order": [],
"processing": true,
"searching" : true,
"orderCellsTop": true,
"language": {
"emptyTable": "No companies found for the selected range."
},
//code to sum up columns...
"headerCallback": function () {
var api = this.api(),
columns = [0,3,4,5]; // Add columns here
for (var i = 0; i < columns.length; i++) {
$('#totals th').eq(columns[i]).html('Total: ' + api.column(columns[i], {filter: 'applied'}).data().sum() + '<br>');
}
}
} );
I have used the sum() api :
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 );
} );
I have tried all the ways to get correct value. I have cross checked the database queries and I am getting the right data.
Hope I have made it clear. Suggestions would be helpful. Thanks
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 ); } );