Datatables find string and add class - datatables

I try to find string in my table and add class to this row. But this code doesn't work. Just nothing happens. Here is my code, latter I call myTable() function:
function myTable() {
var selectDateVar = $('#selectDate').val();
var table = $('#example').DataTable( { // Таблица
"processing": true,
"serverSide": true,
"deferRender": true,
"bDestroy": true,
"sAjaxSource": "server_processing.php?data=30/09/2015",
"order": [[ 2, "desc" ]],
initComplete: function(){
var api = this.api();
new $.fn.dataTable.Buttons(api, {
buttons: [
{
extend: 'print',
text: 'Принтиране',
'className': 'btn-lg btn btn-warning printBTN',
},
]
});
api.buttons().container().appendTo( '.printButton' );
}
});
var indexes = table.rows().eq( 0 ).filter( function (rowIdx) {
return table.cell( rowIdx, 3 ).data() === '180' ? true : false;
} );
table.rows( indexes ).nodes().to$().addClass( 'highlight' );
}
My table:
I use this example https://datatables.net/reference/type/row-selector

function myTable() {
var selectDateVar = $('#selectDate').val();
var table = $('#example').DataTable( { // Таблица
"processing": true,
"serverSide": true,
"deferRender": true,
"bDestroy": true,
"sAjaxSource": "server_processing.php?data=30/09/2015",
"order": [[ 2, "desc" ]],
initComplete: function(){
var api = this.api();
new $.fn.dataTable.Buttons(api, {
buttons: [
{
extend: 'print',
text: 'Принтиране',
'className': 'btn-lg btn btn-warning printBTN',
},
]
});
api.buttons().container().appendTo( '.printButton' );
//filtering code should be inside of initComplete function
//but in your case an empty table is filtered
var indexes = table.rows().eq( 0 ).filter( function (rowIdx) {
return table.cell( rowIdx, 3 ).data() === '180' ? true : false;
} );
table.rows( indexes ).nodes().to$().addClass( 'highlight' );
}
});
}
You need to call the code on data load. Currently you call it before the table is filled with server data. Just add your code sample to initComplete function.
initComplete will be called after the moment Ajax data is loaded.
The answer to the second question: if you need to search across several columns just add the following code:
var indexes = table.rows().eq( 0 ).filter( function (rowIdx) {
return table.cell( rowIdx, 3 ).data() === '180' &&
table.cell( rowIdx, 0 ).data() === '521' ? true : false;
} );

Related

Error occurs only when initializing more than 1 datatable on a page

I'm trying to have 2 datatables on one page.
I'm not initializing them in one function call, however.
I'm initializing them in separate function calls.
I've made a javascript function that looks like this:
function initialize_datatable(args) {
generate_footer(args.table_selector);
$(args.table_selector).DataTable({
columns: args.columns,
order: args.order,
scrollX: true,
...
...
Is it not possible to call this method twice?
Do I need to consolidate multiple tables into one .DataTable() initialization? E.g. $('#table-one #table-two #table-three').DataTable()?
Whenever I try to make two separate calls to .DataTable() I get the following error:
Uncaught TypeError: Cannot set property 'nTf' of undefined. If you Google this error it says this error occurs because you have a differing number of elements in your header and footer. I have counted my <th> elements in my header footer, they are the same number.
I can initialize one table, or the other, but not both at the same time, so I know it's an issue with making multiple calls to .DataTable()
This is the full definition of initialize_datatable:
function initialize_datatable(args) {
generate_footer(args.table_selector);
$(args.table_selector).DataTable({
columns: args.columns,
order: args.order,
scrollX: true,
sScrollXInner: "100%",
dom: "Blfrtip",
buttons: [
{
extend : 'copyHtml5',
title : args.title,
sheetName : args.title,
footer : true,
exportOptions: {
columns: ':visible'
}
},
{
extend : 'excelHtml5',
footer : true,
title : args.title,
sheetName : args.title,
exportOptions: {
columns: ':visible'
}
},
{
extend : 'csvHtml5',
title : args.title,
sheetName : args.title,
footer : true,
exportOptions: {
columns: ':visible'
}
},
{
extend : 'print',
text : 'Print',
title : args.title,
sheetName : args.title,
autoPrint : true,
footer : true,
stripHtml : false,
exportOptions: {
columns: ':visible',
}
}
],
drawCallback: function () {
let api = this.api();
// hide columns that add up to 0
api.columns().every(function (i) {
let sum = this.data().sum();
if (sum === 0 && typeof sum === 'number' && i !== 0) {
api.column(i).visible(0);
}
});
},
footerCallback: function (row, data, start, end, display) {
let api = this.api()
intVal = function (i) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '')*1 :
typeof i === 'number' ?
i : 0;
}
api.columns({page: 'current'}).every(function (i) {
let columnTotal = this.data().reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
if (!isNaN(columnTotal)) {
columnTotal = Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD'}).format(columnTotal);
$(this.footer()).html(columnTotal);
}
})
}
});
}

Get value and pass to parameter datables

So I have datetimepicker. And I have datatable like the following code
var table = $("#tbllogvisitor");
var target = table.attr('data-table');
var date = $("#datetimepicker3").data("date");
var oTable = table.on( 'processing.dt', function ( e, settings, processing ){
if (processing) {
$(this).find('tbody').addClass('load1 csspinner');
} else{
$(this).find('tbody').removeClass('load1 csspinner');
};
}).DataTable({
"bServerSide": true,
"paging": false,
"filter": false,
"scrollCollapse": true,
"ordering": false,
"ajax": {
"url" : "../ajax/datatable",
"type": "POST",
"data" :{
target: function() { return target },
tanggal: function() { return date }
}
}
});
Well is working, and then I wanna trigger datetimepicter if I'm changing my datetimepicter value with the following code :
$("#datetimepicker3").on("dp.change", function (e) {
oTable.ajax.reload();
});
But the paramater variable of datetimepicker still not change at all, still same at first time. How do Ii pass my value datetimepicker and reload the datatable?
Sorry for my bad english.

Column Visibility is not restored from a saved state via stateLoadCallback

I have added the Column Visibility button to choose to show or hide certain columns. I'm saving the state in a database, I call the stateSaveCallback function via a click on a button.
I cant find documentation about retrieving data this way, so I just link to the page and pass variables to get the data back from the database, and then load that using stateLoadCallback.
Now all this works fine, EXCEPT the column visibility is not restored. It is in the JSON data being returned though.
Here is my full code:
$(document).ready(function() {
$.extend( jQuery.fn.dataTableExt.oSort, {
"date-uk-pre": function (a){
return parseInt(moment(a, "DD/MM/YYYY").format("X"), 10);
},
"date-uk-asc": function (a, b) {
return a - b;
},
"date-uk-desc": function (a, b) {
return b - a;
}
});
var edit_date_col_num = $('th:contains("Edit Date")').index();
var entry_date_col_num = $('th:contains("Entry Date")').index();
var table = $('.mainTable').DataTable( {
pageLength: 50,
colReorder: true,
stateSave: true,
columnDefs: [
{ "type": "date-uk", targets: [ edit_date_col_num, entry_date_col_num ] }
],
dom: 'Blfrtip',
buttons: [
'copy', 'csv', 'excel', 'print',
{
extend: 'colvis',
collectionLayout: 'fixed four-column',
postfixButtons: [ 'colvisRestore' ]
}
],
<?php
$id = $this->input->get('id');
$action = $this->input->get('action');
if(isset($action) && $action == 'load' && isset($id) && $id != '') :
?>
"stateLoadCallback": function (settings) {
var o;
// Send an Ajax request to the server to get the data. Note that
// this is a synchronous request since the data is expected back from the
// function
$.ajax( {
"url": EE.BASE + "&C=addons_modules&M=show_module_cp&module=ion&method=state_save&action=load&id=<?php echo $id;?>",
"async": false,
"dataType": "json",
"success": function (response) {
response = JSON.parse(response);
o = response;
}
});
return o;
},
<?php
endif;
?>
initComplete: function (settings) {
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>' )
} );
} );
// Need to re-apply the selection to the select dropdowns
var cols = settings.aoPreSearchCols;
for (var i = 0; i < cols.length; i++)
{
var value = cols[i].sSearch;
if (value.length > 0)
{
value = value.replace("^", "").replace("$","");
console.log(value);
$("tfoot select").eq(i).val(value);
}
}
},
} );
// Save a datatables state by clicking the save button
$( ".save_state" ).click(function(e) {
e.preventDefault();
table.destroy();
$('.mainTable').DataTable( {
colReorder: true,
stateSave: true,
"stateSaveCallback": function (settings, data) {
var save_name = $('.save_name').val();
// Send an Ajax request to the server with the state object
$.ajax( {
"url": EE.BASE + "&C=addons_modules&M=show_module_cp&module=ion&method=state_save&action=save&save_name="+save_name,
"data": data,
"dataType": "json",
"type": "POST",
"success": function (response)
{
//console.log(response);
}
} );
},
});
//table.state.save();
window.location.replace(EE.BASE + "&C=addons_modules&M=show_module_cp&module=ion&method=applications");
});
$( ".clear_state" ).click(function(e) {
e.preventDefault();
table.state.clear();
window.location.replace(EE.BASE + "&C=addons_modules&M=show_module_cp&module=ion&method=applications");
});
} );
Here is the saved JSON with several visible false in the beginning (which are visible once loaded):
{"time":"1449338856556","start":"0","length":"50","order":[["0","asc"]],"search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"},"columns":[{"visible":"false","search":{"search":"","smart":"false","regex":"true","caseInsensitive":"true"}},{"visible":"false","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"false","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"false","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"false","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}},{"visible":"true","search":{"search":"","smart":"true","regex":"false","caseInsensitive":"true"}}],"ColReorder":["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59","60","61","62","63","64","65","66","67","68","69","70"]}
Thanks
In my case datatables rejects old data according to "stateDuration" and "time" properties..
Solution: ignore state duration
"stateSave": true,
"stateDuration": -1,
Above case:
"visible":"false" may should be "visible":false
After a while of debugging this myself here's what worked for me..
This issue is that all the values in your JSON are strings and they need to be of correct datatypes for the datatables plugin.
Within the "stateSaveCallback" ajax request to save your state I did the following to the json string and then it saved all the values properly which then loaded the state as it should.
"stateSaveCallback": function (settings, data) {
var save_name = $('.save_name').val();
// Send an Ajax request to the server with the state object
$.ajax( {
"url": EE.BASE + "&C=addons_modules&M=show_module_cp&module=ion&method=state_save&action=save&save_name="+save_name,
//"data": data,
"data": JSON.stringify(data), // change to this..
"dataType": "json",
"type": "POST",
"success": function (response)
{
//console.log(response);
}
} );
},

Export all table data using jquery dataTables TableTools

I am doing server side processing using jquery datatable.My datatable code is as below:
$('#DataGrid').dataTable({
destroy: true,
"processing": true,
searching: false,
serverSide: true,
"scrollX": true,
"bLengthChange": false,
"iDisplayLength": pageSize,
"bInfo": true,
//stateSave: true,
order: [
[0, "desc"]
],
"aoColumnDefs": [{
'bSortable': false,
'aTargets': [(lastColumn - 1)]
}],
"dom": 'T<"clear">lfrtip',
"tableTools": {
"aButtons": [
"copy",
"csv", "xls", "pdf"
],
"sSwfPath": $("body").attr("data-project-root") + "Content/TableTools-2.2.3/swf/copy_csv_xls_pdf.swf"
},
ajax: {
url: 'StudentProgramListForIdCardResult',
type: 'POST',
data: function(d) {
d.programId = programId;
d.sessionId = sessionId;
d.branchId = branchId;
d.campusId = campusId;
d.batchName = batchName;
d.course = course;
if ($('#paymentStatus').val() > 0) {
d.paymentStatus = $('#paymentStatus').val();
} else {
d.paymentStatus = paymentStatus;
}
if ($('#imageStatus').val() > 0) {
d.imageStatus = $('#imageStatus').val();
$('#imageStatus').val();
} else {
d.imageStatus = imageStatus;
}
if ($('#printingStatus').val() > 0) {
d.printingStatus = $('#printingStatus').val();
} else {
d.printingStatus = printingStatus;
}
d.informationViewList = informationViewList;
d.batchDays = batchDays;
d.batchTime = batchTime;
}
}
});
But when I export data, TableTools is exporting the data in current page. It is not loading all data in the table.
The dataTables plugin is great and all, but the underlying table/table rows are still there in the DOM and can be traversed the same way you'd traverse any HTML table:
//foo will be a nodeList of all the tr's in the table
var foo = document.getElementById('#DataGrid').querySelectorAll('tr');
var i = 0, string = '', len = foo.length, row, cells;
for (;i<len; ++i) {
row = foo[i];
cells = row.children; //td's
string += 'however you want to package it for your ajax';
}
$.post({url: 'myServerScript', {data: string}, callback});
I was unable to easily find any documentation on a plugin-implemented appropriate export, all the export examples seem to focus on excel/csv saved to the local drive.

Jeditable + Datatables + Server Side Processing

I have this piece of code...
$(document).ready(function() {
var oTable = $('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "../listagem/listar_manuais.php",
"sPaginationType": "full_numbers",
"fnDrawCallback": function () {
$('td', this.fnGetNodes()).editable( 'update.php', {
"callback": function( sValue, y ) {
var aPos = oTable.fnGetPosition( this );
oTable.fnUpdate( sValue, aPos[0], aPos[1] );
},
"submitdata": function ( value, settings ) {
return { "row_id": this.parentNode.getAttribute('id') };
},
"height": "14px"
} );
}
});
} );
What it does is the server side search of Datatables...
My problem, is that i don't kno what to do from here, to get the Jeditable functional with the server side processing...
Can anyone help? :s
The values will be in the HTTP Request object in your update.php. Your updated value is in "value", row_id in "row_id" according to your code above.