I have the below working code for data table to set cell color based on condition.
$(document).ready(function() {
// DataTable
var table = $('#example').DataTable({
/*
dom: 'Bfrtip',
buttons: ['excel',{
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'LEGAL' }],
"ordering": false,
language: {
search: "_INPUT_",
searchPlaceholder: "Search All Data"
} */
rowCallback: function(row, data, index) {
console.log(row)
if (data[12].split(';')[1] == "In Progress") {
$(row).find('td:eq(11)').addClass('color')
}
}
});
});
The above code works fine but if I remove the comments section which is to add export function, it doesn't work.
I tried reproducing the same issue you're facing. I've created a jsfiddle example, which is working nice and fine. The only thing I changed in your code is that I added a comma (,) before rowCallback, this way :
$('#example').DataTable({
dom: 'Bfrtip',
buttons: ['excel',{
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'LEGAL' }],
"ordering": false,
language: {
search: "_INPUT_",
searchPlaceholder: "Search All Data"
},
rowCallback: function(row, data, index) {
console.log(row)
if (data[12].split(';')[0] == "In Progress") {
$(row).find('td:eq(11)').addClass('color')
}
}
});
and Plus, do recheck that the files related to jQuery datatable are same as the files I've added in my jsfiddle , there is a possibility that you've added a file twice or you might be using an older version of Jquery. If the issue still persists, edit your question and add your html + the files related to jquery that you've initialized.
Related
I have a datatable that gets called in a function like this:
function createDatatable(){
//get table data
var resp = getTableData()
var dataset = resp.data //table data
var total = resp.total //number like 238
//if table already exists
if (myProductGapsTable) {
myProductGapsTable.clear();
myProductGapsTable.rows.add(dataset); //add new dataset
//myProductGapsTable.language.reload(); //trying to get something like this to work
myProductGapsTable.draw();
} else {
//create table
myProductGapsTable = $('#myProductGapsTable').DataTable({
scrollY: "60vh",
scrollX: true,
scrollCollapse: true,
paging: false,
fixedColumns: true,
"autoWidth": true,
data: dataset,
retrieve: false,
"language": {
"emptyTable": "No table data availiable.",
"info": `Showing _START_ to _END_ of ${total} entries`,
},
"sDom": 'ti',
"paging": false,
"preDrawCallback": function (settings) {
pageScrollPos = $("#myProductGapsTableContainer div.dataTables_scrollBody").scrollTop();
},
"drawCallback": function (settings) {
$("#myProductGapsTableContainer div.dataTables_scrollBody").scrollTop(pageScrollPos);
},
buttons: [
{
extend: 'excelHtml5',
text: 'excel',
exportOptions: { rows: { selected: true, search: 'applied' } }
},
{
extend: 'csvHtml5',
text: 'csv',
exportOptions: { rows: { selected: true, search: 'applied' } }
},
],
select: {
style: 'multi',
selector: 'td:first-child',
search: 'applied'
},
order: [1, 'asc'],
});
}
}
I am trying to have the info field use a custom total number for the info footer, this works fine when the table is first created; it will load the number (238 initially) in the footer correctly. But when I call the function again, if the total number is changed (like now lets say total is 77), the footer info text will not show the updated 'out of 77' text that I would like it to have.
I have an if statement that checks if the table has already been created when the function is called, is there any way I can refresh or reload the table's language field? So I can refresh the table's lower dom info text when the if statement is called?
I don't know of a way to do this using the DataTables API, unfortunately, but here is a jQuery/DOM way:
function changeCountTotal() {
total = resp.total;
var info = $('#myProductGapsTable_info').html();
// Format is assumed to be: "Showing 1 to 10 of 1,234 entries"
var regex = /(Showing.*of ).+?( entries)/;
var updatedinfo = info.replace(regex, "$1" + total + "$2");
$('#example_info').html(updatedinfo);
}
This would need to be called after the redraw peformed by myProductGapsTable.draw();, to ensure the other parameters (_START_, _END_) are correctly re-evaluted by DataTables.
If you want to format the total for thousands separators (or whatever is appropriate for your locale), that would be something like this:
total = resp.total.toLocaleString()
(If there is a way to do this using the DataTables API, that would be a better answer, of course.)
I have these two codes and one cancels the other. I need help getting the two together. Thanks
<script type="text/javascript" class="init">
$(document).ready(function() {
var table = $('#escritorios').DataTable({
lengthChange: false,
buttons: ['colvis', 'print', 'copy', 'excel', 'pdf']
});
table.buttons().container().appendTo('#example_wrapper .col-md-6:eq(0)');
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#escritorios').DataTable({
responsive: {
details: {
type: 'column',
target: 'tr'
}
},
columnDefs: [{
className: 'control',
orderable: false,
targets: 0
}],
order: [1, 'asc']
});
});
</script>
Looks like you are trying to reinitialise a datatable with same ID. To reinitialise a datatabe you have to destroy it first.
if ($.fn.DataTable.isDataTable('#Table')) {
$('#Table').DataTable().destroy();
}
The issue is because you're initialising the DataTable() library on the same element multiple times, which is invalid, and causes the error you see.
To fix this combine all the settings in to a single call, like this:
jQuery(function($) {
var table = $('#escritorios').DataTable({
lengthChange: false,
buttons: ['colvis', 'print', 'copy', 'excel', 'pdf'],
responsive: {
details: {
type: 'column',
target: 'tr'
}
},
columnDefs: [{
className: 'control',
orderable: false,
targets: 0
}],
order: [1, 'asc']
});
table.buttons().container().appendTo('#example_wrapper .col-md-6:eq(0)');
});
I have a jQuery datatable that is initially populated using ajax call, and when i click anywhere on the table like pagination number or display length dropdown list, the whole page is reloaded indefinetely. Here is how i populate the datatable.
let table = $('#data-table').DataTable();
function populateTable(){
table = $('#data-table').DataTable({
destroy: true,
responsive: true,
serverSide: false,
autoWidth: false,
paging: true,
filter: true,
searching: true,
stateSave: true,
scrollX: true,
lengthMenu: [10, 25, 50, 75, 100],
language: {
"search": "Filtrer: "
},
ajax: {
url: '/Observer/GetActiveClientsByFloor',
type: 'POST',
data: {
FloorId: floorId,
Type: type
},
dataSrc: ''
},
columns: [
{
title: 'Zone',
data: 'LastKnownZone',
},
{
title: 'HiƩrarchie Map',
data: 'MapInfo.mapHierarchyString',
},
{
title: 'Addresse MAC',
data: 'macAddress',
},
{
title: 'SSID',
data: 'ssId',
},
],
createdRow: (row, data, dataIndex, cells) => {
const selectedRowProfileId = $('#selectedRowProfileId', window.parent.document).val();
if (selectedRowProfileId !== '') {
if (data['ProfileId'] === selectedRowProfileId) {
$(row).addClass('selectedCustom');
}
}
},
initComplete: function (settings, json)
{
const response = json;
//Show the respone on other part of the page
}
}).order([[1, 'asc']]).draw(false);
}
I would like to know what could be causing page re-load and also know how to make pagination works.
You don't need to call order([[1, 'asc']]).draw(false) after table initialization, just add
order: [[1, 'asc']]
to your table properties, like this
$(document).ready(function(){
let table = $('#data-table').DataTable({
order: [[1, 'asc']],
//Other properties
});
As you are not using server-side DataTables will make pagination automatically when you click pagination buttons, considering that all data has already been loaded in the first Ajax call, but when serverSide is set to true every time you change the pagination a new Ajax call will be made by datatables sending aditional parameters for pagination, ordering etc and you will need to change you backend query, filters and pagination logic based on that params.
Edit:
Also destroy: true is not needed in your case, as Documentation says:
"Destroy any existing table matching the selector and replace with the new options."
You are not re-creating or replacing your table, so you can just remove it
I am using jQuery DataTables with Grouping and Filtering on data. But both can't work together. Only one can work.
oTable = $('#schedule').dataTable({
'bLengthChange': false,
'bPaginate': false,
'bJQueryUI': true,
'processing': true,
"aoColumnDefs": [
{ "bSortable": false, "aTargets": ["no-sort"] }
]
}).columnFilter({
sPlaceHolder:"head:before"
}).rowGrouping({
sGroupingColumnSortDirection: "desc",
bExpandableGrouping: true,
bExpandSingleGroup: false,
iExpandGroupOffset: -1,
asExpandedGroups: ['Pending Action', 'In Operation']
});
Please give me advice on how to work with both and I want to add the filter field in different div.
It doesnt work because you are using chaining. You are accidently trying to initialise rowGrouping on whatever columnFilter() returns :
dataTable().columnFilter().rowGrouping()
< dataTable < columnFilter
Use another approach to initialise the plugins, for example in the initComplete callback (fnInitComplete if you are using 1.9.x) :
var table = $('#example').dataTable({
initComplete : function() {
this.columnFilter();
this.rowGrouping({
bExpandableGrouping: true,
asExpandedGroups: ["Other Browsers", "Trident"],
fnOnGrouped: function() { alert('Rows are regrouped!'); }
});
}
})
demo -> http://jsfiddle.net/y2s2b0an/
I am using jQuery DataTables 1.10 and all my code is working fine. To add export functionality I refer this link. I have added all the files what is said
//code.jquery.com/jquery-1.11.3.min.js
https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js
https://cdn.datatables.net/buttons/1.0.3/js/dataTables.buttons.min.js
//cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js
//cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/pdfmake.min.js
//cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js
//cdn.datatables.net/buttons/1.0.3/js/buttons.html5.min.js
//cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css
//cdn.datatables.net/buttons/1.0.3/css/buttons.dataTables.min.css
I have downloaded these files and stored locally. So my final code is like :
table = $(".jqueryDataTable").DataTable( {
"initComplete": function(oSettings, json) {
alert( 'DataTables has finished its initialisation in table.' );
this.fnHideEmptyColumns(this);
$('#lblReportHeader').html(reportHeader);
$('#lblFromDate').html(fromDateHeader);
$('#lblToDate').html(fromToHeader);
$('#tblReportHeader').show();
},
"searching": false,
"retrieve": true,
"destroy": true,
"ajax": "./getReportDetails",
"jQueryUI": true,
"dom": 'r<"H"lf><"datatable-scroll"t><"F"ip>',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
],
"fnServerParams": function ( data ) {
newData=data;
newData.push( { "name": "reportType", "value": reportType }, { "name": "reportSubType", "value": reportSubType}, { "name": "fromDate", "value": fromDate}, { "name": "toDate", "value": toDate});
},
"columns": [
{ "mData": "username", "sTitle": "username"},
{ "mData": "transferType", "sTitle": "transferType"},
{ "mData": "fromAccount", "sTitle": "fromAccount"}
]
} );
But it is not showing any export button on my UI.
What is the wrong in my code ?
I had the same issues where everything looked good from adding required javascript and css files to specifying "dom" value and initializing buttons array in the data table body. However, my root cause of not displaying the buttons was that I was adding one of the dependent javascripts two times and same js file was placed in two different locations inside my resources folder. As soon as I identified and remove additional duplicate js reference, the problem got resolved and I was able to see the buttons displayed and working as well.
Here issue is you have included required JS files but at the time of initialization, you haven't specified options for export like mentioned below:
$('#example').DataTable( {
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
You can remove the options from copy, csv, excel, pdf, print according to requirement.
You cannot change the name of button, it needs to be exact same as mentioned.