How can have multirows Footer in Datatables? - javascript

I want make two rows at my footer datatables. First row of footer for sum columns and second row of footer for search columns.
This is my code in javascript
$(function () {
$('#ntable1 tfoot th').each( function () { //for search columns in footer
var title = $(this).text();
$(this).html( '<input type="text" placeholder="'+title+'"/>' );
} );
var table = $("#ntable1").DataTable({
"responsive": false, "scrollX": true, "lengthChange": true, "autoWidth": false,
"buttons": [
{
extend: 'copy',
exportOptions: {
columns: [':visible' ]
}
},
{
extend: 'excel',
exportOptions: {
columns: [':visible' ]
},
messageBottom: textTop,
},
{
extend: 'print',
footer: true,
exportOptions: {
columns: [':visible' ]
},
messageTop: textTop
},
{
extend: 'colvis',
exportOptions: {
columns: [':visible' ]
}
}
],
footerCallback: function (row, data, start, end, display) { //for sum of columns in footer
var api = this.api();
// 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(3)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
// Total over this page
pageTotal = api
.column(3, { page: 'current' })
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
// Update footer
$('tr:eq(0) td:eq(3)', api.table().footer()).html(format('$' + pageTotal + ' ( $' + total + ' total)')); //not work
// $(api.column(3).footer()).html('$' + pageTotal + ' ( $' + total + ' total)'); //not work
},
initComplete: function () {
// Apply the search
this.api().columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change clear', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
} );
} );
}
}).buttons().container().appendTo('#ntable1_wrapper .col-md-6:eq(0)');
});
Datatables code in html
<table id="ntable1" class="table table-bordered table-striped">
<thead> ... </thead>
<tbody> ... </tbody>
<tfoot>
<tr> <!-- for sum columns -->
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr> <!-- for search columns -->
<th>No</th>
<th>Nama Program</th>
<th>Tahun</th>
<th>Jumlah Kota</th>
<th>Nama Kota</th>
<th>Jumlah Sekolah</th>
<th>Jumlah Siswa</th>
<th>Pre Test</th>
<th>Post Test</th>
<th>%</th>
<th>Tingkat Kepuasan</th>
<th>Tabungan Pelajar (Account)</th>
</tr>
</tfoot>
</table>
If I add row in footer, my search column doesn't work. My problem only how to have multiple rows in footer datatables, which first row for calculate sum and second row for search column. Hope anyone can help.

Related

Jquery datatables - How count numbers of rows?

I am using to Jquery datables to create a table with row details . Everything working fine Only the number of entries
The current logic is counting the parents row + child rows. I want to count only parents rows which are 4. My result should be Showing 1 to 10 of 4 entries.
In my Json file, I have recordsTotal: 16 which is the total rows parents + child. When I change to 4 which is number of parents rows the table will show me only first record (Ticket id 1 + its 3 child rows ) as it's counted as 4 entries.
Any suggestions please how can I update ? Thank you.
$(document).ready(function() {
function format ( d ) {
d.Items.sort(function compare(a,b) {
if (a.Line_No < b.Line_No)
return -1;
if (a.Line_No > b.Line_No)
return 1;
return 0;
});
var x = '<table class="nowrap table table-bordered table-hover" cellspacing="0" width="100%"><thead><tr><th>Line No</th><th>Line Level Issue</th><th>Created Date</th><th>Created By</th></tr></thead><tbody>' ;
$.each(d.Items, function( index, value ) {
x += '<tr><td>' + d.Items[index].Line_No + '</td><td>' + d.Items[index].Line_Level_Issue + '</td><td>' + d.Items[index].Created_Date + '</td><td>' + d.Items[index].Created_By + '</td></tr>';
});
x +='</tbody></table>';
return x;
}
var dt = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"deferRender": true,
"lengthChange": true,
"pageLength": 10,
"language": { "emptyTable": "No matching records found",
"info": "Showing _START_ to _END_ of _TOTAL_ entries",
"zeroRecords": "No matching records found" },
"ajax": "https://api.myjson.com/bins/vwjfc",
"columns": [
{
"class": "details-control",
"data": "Ticket_id"
,render : function(data, type, row) {
return ' ' + data;
}
},
{ "data": "Order_Level_Issue" },
{ "data": "Geo" },
{ "data": "Region" },
{ "data": "Territory" },
{ "data": "Market" },
{ "data": "Country" },
{ "data": "SoldTo_Number" },
{ "data": "SoldTo_Name" },
{ "data": "Order_Numer" }
],
"order": [[0, 'asc'],[1, 'asc']]
} );
var detailRows = [];
$('#example tbody').on( 'click', 'tr td.details-control', function () {
var tr = $(this).closest('tr');
var row = dt.row( tr );
var idx = $.inArray( tr.attr('id'), detailRows );
if ( row.child.isShown() ) {
tr.removeClass( 'details' );
row.child.hide();
detailRows.splice( idx, 1 );
}
else {
tr.addClass( 'details' );
row.child( format( row.data() ) ).show();
if ( idx === -1 ) {
detailRows.push( tr.attr('id') );
}
}
} );
dt.on( 'draw', function () {
$.each( detailRows, function ( i, id ) {
$('#'+id+' td.details-control').trigger( 'click' );
} );
} );
} );
td.details-control {
background: url('https://datatables.net/examples/resources/details_open.png') no-repeat center left;
cursor: pointer;
}
tr.details td.details-control {
background: url('https://datatables.net/examples/resources/details_close.png') no-repeat center left;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet"/>
<table id="example" class="nowrap table table-hover table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>TicketT id</th>
<th>Order Level Issue</th>
<th>Geo</th>
<th>Region</th>
<th>Territory</th>
<th>Market</th>
<th>Country</th>
<th>SoldTo Number</th>
<th>SoldTo Name</th>
<th>Order Numer</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Ticket id</th>
<th>Order Level Issue</th>
<th>Geo</th>
<th>Region</th>
<th>Territory</th>
<th>Market</th>
<th>Country</th>
<th>SoldTo Number</th>
<th>SoldTo Name</th>
<th>Order Numer</th>
</tr>
</tfoot>
</table>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
I assume the problem was not dataTables at all but your ajax call, since you are using serverSide your server side is the one who sends the data the table will display including the total of records so in your ajax response you have:
{draw: 1, recordsTotal: 16, recordsFiltered: 16, data: Array(4)}
So all you have to do is work in your server side script in order the reflect the expected output.
Hope it helps

Individual column searching (text inputs) not working in my rails code

Individual column searching (text inputs) is not working in my rails code.
My mappings.js file :
$(document).ready(function(){
$("table[role='example_datatable']").each(function(){
var dataTableInstance = $('#mappings').DataTable({
"order": [[ 4, "desc" ]],
columnDefs: [
{ "searchable": false, "targets": 6},
{ "orderable": false, "targets": 6}
],
"bFilter": false,
dom: 'Bfrtip',
pageLength: 10,
processing: true,
serverSide: true,
ajax: $(this).data('url')
});
$('#mappings tfoot th').each(function(){
var title = $('#mappings thead th').eq($(this).index()).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" name="'+title+'" />' );
});
dataTableInstance.columns().every(function () {
alert("hi");
var datatableColumn = this;
$(this.footer()).find('input').on('keyup', function () {
alert("hi2");
datatableColumn.search(this.value).draw();
});
});
});
})
My mappings.html.erb file:
<%= content_tag :table,
role: :example_datatable,
id: 'mappings',
class: 'table reconciletable table-striped table-bordered table-hover',
data: { url: mappings_path(format: :json)} do %>
<tfoot>
<tr>
<th>Id</th>
<th>Entity</th>
<th>Item</th>
<th>Group</th>
<th>Record Created On</th>
<th>Record Created By</th>
</tr>
</tfoot>
<thead>
<tr>
<th>Id</th>
<th>Entity</th>
<th>Item</th>
<th>Group</th>
<th>Record Created On</th>
<th>Record Created By</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
<% end %>
I'm able to get the input texts for each column but once I try searching & nothing happens and it's not able to filter my datatable according to column search.
This is my code. please help me out :'(
Try this
//Apply the search
table.columns().eq( 0 ).each( function ( colIdx ) {
$( 'input', table.column( colIdx ).footer() ).on( 'keyup change', function () {
table
.column( colIdx )
.search( this.value )
.draw();
} );
} );
working Demo

Showing 0 to 0 of 0 entries in DataTable

Hi I am new and i am using dataTable to display my, mysql data.So My Data are display correctly but here my dataTable footer doesn't work correctly.
Here is my code
UI_CRUD.prototype.refreshTable = function(params = {}){
var tableBody = $('.view-datatable tbody');
var dataUrl = this.moduleURL+'/alenter code herel';
var title = this.moduleTitle;
// console.log(this.moduleTitle);
console.log('all ..');
$.ajax({
url: dataUrl,
data : params,
})
.done(function(data) {
var html = '';
$.each(data, function(index, item) {
html+= '<tr>';
$.each(item, function(index, data) {
(index != 'id') ? html+= '<td>'+data+'</td>' : html+='';
});
html+= '<td class="actions">' +
'<i class="icon-eye text-primary view-btn" data-id="'+item.id+'">'+
'</i>'+
'<span></span>'+
'<i class="icon-pencil7 text-primary edit-btn" data-id="'+item.id+'">' +
'</i>'+
'<span></span>'+
'<i class="icon-bin sweet_combine text-danger delete-btn" data-id="'+item.id+'">' +
'</i>'+
'</td>';
html+= '</tr>';
});
tableBody.html(html);
})
.fail(function(res) {
console.error(res,'UI_CRUD ERR : ');
});
}
This is the table in blade file.
<table class="table view-datatable" id="mytable">
<thead>
<tr>
<th>Company Code </th>
<th>Company Name </th>
<th>Company Address </th>
<th>Telephone No. </th>
<th>Fax No. </th>
<th style="text-align: center;">Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
this is the laravel controller
public function getAll()
{
$company = $this->getCompanies();
return response()->json($company,200);
}
public function getCompanies()
{
$company = Company::select("id", "CO_COMCODE", "CO_NAME",
DB::raw("CONCAT(CO_ADD1, ',', CO_ADD2, ',', CO_ADD3, ',', CO_ADD4) AS Address"),
"CO_TELNO", "CO_FAXNO")
->get();
return $company;
}
This is response json
[{"id":39,"CO_COMCODE":"FFDE","CO_NAME":"dsfsdf","Address":"‌​fsdfsd,fsdf,fdsf,fsd‌​f","CO_TELNO":"12345‌​6789","CO_FAXNO":"12‌​3456789"},{"id":41,"‌​CO_COMCODE":"AAAA","‌​CO_NAME":"fdfdsf","A‌​ddress":"dsfdsf,dfds‌​f,dsffdsf,fdsfsd","C‌​O_TELNO":"123456789"‌​,"CO_FAXNO":"1234567‌​89"}]
This is My Output page
This is the response
JSon Response preview and
JSon Response
After many efforts, I fixed error
Issues was with applying dataTable plugin. After I remove that js file and add new dataTable.
<table class="table view-datatable">
<thead>
<tr>
<th>Company Code </th>
<th>Company Name </th>
<th>Company Address </th>
<th>Telephone No. </th>
<th>Fax No. </th>
</tr>
</thead>
<tbody></tbody>
var table = $('.view-datatable').DataTable( {
"processing" : true,
"retrieve": true,
"ajax" : {
"url" : ajax_url
},
"columns" : [ {
"data" : "CO_COMCODE"
}, {
"data" : "CO_NAME"
}, {
"data" : "Address"
}, {
"data" : "CO_TELNO"
}, {
"data" : "CO_FAXNO"
}, {
data: null,
className: "dataTable-center",
},],
"rowCallback": function( row, data, index ) {
$('td:eq(5)', row).html(
'<i class="icon-eye text-primary view-btn" data-id="'+data.id+'">'+
'</i>'+
'<span> </span>'+
'<i class="icon-pencil7 text-primary edit-btn" data-id="'+data.id+'">' +
'</i>'+
'<span> </span>'+
'<i class="icon-bin sweet_combine text-danger delete-btn" data-id="'+data.id+'">' +
'</i>'
);
},
"pagingType": "full_numbers",
buttons: {
buttons: [
{
extend: 'colvis',
className: 'btn btn-default'
},
{
text: 'Add New',
className: 'add-new btn bg-blue-800 ui-add-new',
action: function(e) {
// UI_addModel('show');
}
},
{extend: 'copy'},
// {extend: 'csv'},
{extend: 'excel'},
{extend: 'pdf'},
{extend: 'print'}
]
}
} );

unable to display sum in footer using datatable

I have created a datatable using jQuery. The table has seven columns , among one column is for Grand Total (column 6). I have to display the sum of Grand Total (column 6) in the Grand Total (column 6) at the bottom of Grand Total (column 6).
How can I do that? I have tried some code but nothing worked.
Outout is blank column.
here is the code that I found.
below is the html code
HTML
<table class="display table table-bordered table-striped" id="dynamic-table">
<thead>
<tr>
<th>Invoice Type</th>
<th>Invoice No</th>
<th>Invoice Date</th>
<th>Customer Name</th>
<th>City </th>
<th>Grand Total</th>
<th class="hidden-phone">Action</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th>Total:</th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
JavaScript
function load_datatable() {
var data = $('input[name=report]:Checked').val();
var date = $('#rep_date').val();
var type = $('#type_id').val();
datatable = $("#dynamic-table").dataTable({
"bAutoWidth": false,
"bFilter": true,
"bSort": true,
"bProcessing": true,
"bDestroy": true,
"bServerSide": true,
"oLanguage": {
"sLengthMenu": "_MENU_",
"sProcessing": "<img src='" + root_domain + "img/loading.gif'/> Loading ...",
"sEmptyTable": "NO DATA ADDED YET !",
},
"aLengthMenu": [
[10, 20, 30, 50],
[10, 20, 30, 50]
],
"iDisplayLength": 10,
"sAjaxSource": root_domain + 'app/invoice/',
"fnServerParams": function(aoData) {
aoData.push({
"name": "mode",
"value": "fetch"
}, {
"name": "report",
"value": data
}, {
"name": "type_id",
"value": type
}, {
"name": "date",
"value": date
});
},
"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 this page
pageTotal = api
.column(5, {
page: 'current'
})
.data()
.reduce(function(a, b) {
return intVal(a) + intVal(b);
}, 0);
console.log(pageTotal);
// Update footer
$(api.column(5).footer()).html('$' + pageTotal);
},
"fnDrawCallback": function(oSettings) {
$('.ttip, [data-toggle="tooltip"]').tooltip();
}
}).fnSetFilteringDelay();
//Search input style
$('.dataTables_filter input').addClass('form-control').attr('placeholder', 'Search');
$('.dataTables_length select').addClass('form-control');
}
do this example :
const Table = $('#foo').DataTable({
. . . . . .,
. . . . . .,
drawCallback: function(){
Table.columns(5, {
page: 'current'
}).every(function() {
var sum = this
.data()
.reduce(function(a, b) {
var x = parseFloat(a) || 0;
var y = parseFloat(b) || 0;
return x + y;
}, 0);
console.log(sum);
$(this.footer()).html(sum);
});
}
});
in this case the column was column number 5

Datatable Print Customization

My datatable when printed has the date of printing on top. I want to change the format of that date to dd/mm/yy hh:mm. I have used javascript to initialize the title for datatable, but it appears in the header of the printed page as well as above the table. Also, in the footer of the printed page, I want to display my website name. I couldn't find options to manipulate these. Any help would be appreciated. Thank you.
$(document).ready(function() {
var handleDataTableButtons = function() {
if ($("#report").length) {
$("#report").DataTable({
initComplete: function() {
this.api().columns().every(function() {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function() {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function(d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
},
dom: "Bfrtip",
buttons: [
{
extend: "excel",
className: "btn-sm"
},
/* {
extend: "pdfHtml5",
className: "btn-sm"
},*/
{
extend: "print",
className: "btn-sm",
message: 'Message',
title: 'Some title',
customize: function(win) {
$(win.document.body).find('table')
.addClass('compact')
.css('font-size', '10pt');
}
},
],
responsive: true
});
}
};
TableManageButtons = function() {
"use strict";
return {
init: function() {
handleDataTableButtons();
}
};
}();
TableManageButtons.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<table id="report">
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data1</td>
<td>Data2</td>
</tr>
</tbody>
</table>

Categories