jquery datatable highlight drops off after reload - javascript

I have a datatable which uses ajax to load the values.
var table = $('#example').DataTable({
"ajax": "xxxxxx.aspx",
stateSave: true,
"aLengthMenu": [
[10, 25, 50, 100],
[10, 25, 50, 100]
],
"iDisplayLength": 25,
"order": [
[0, "desc"]
],
columnDefs: [{
"visible": false,
"targets": [2, 3]
}, {
"type": 'date-uk',
"targets": [1, 9, 10]
}, {
"type": 'title-string',
"targets": [11]
}],
});
$('#example tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
using setInterval, I am asking that table to be reloaded every 5 secs.
setInterval(function(){table.ajax.reload(null, false)}, 5000);
When the Datatable is reloaded, it drops off the highlight row. Can anyone please tell me how to retain the highlight on the row after the reload?
Thanks

You could do something like that :
function highlight() {
$('#example tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
}
$(document).ready(function () {
// Call the function at document ready
highlight();
// Call the ajax and the function every 5 seconds
setInterval( function () {
table.ajax.reload(null, false);
highlight();
}, 5000 );
});

Related

How can I decode JSON Unicode using jQuery in a Select2 dropdown filter

I am using Select2 JS and Datatables JS. The data is in JSON format. The data for one value should display as Animal & Veterinary. In JSON it appears as Animal \u0026amp; Veterinary. The Select2 filter displays it as Animal & Veterinary. How can I add a function to the JS below that will decode the Unicode? Below is a function that can work but I dont know how to add it to the JS below.
var title = 'Animal & Veterinary';
function stringToSlug (title) {
return title.toLowerCase().trim()
.replace(/&/g, 'and')
}
Below is the script. This is where I would like to pass the function into the filter. "select2config"
jQuery( document ).ready( function($) {
'use strict';
// Check condition first if the table class exists then run this init.
if ($('.lcds-datatable--advisory-committee-materials').length > 0) {
let pageClass = function () {
let el = $( 'ul.pagination' ).addClass('pagination-sm');
}
// define order of table's control element
let domStyling = "<'row'<'col-sm-12'lB>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>";
var otable9 = $('table.lcds-datatable--advisory-committee-materials').DataTable( {
// Sort of first date column descending.
order: [[0, 'desc']],
deferRender: true,
deferLoading: 50,
dom: domStyling,
ajax: {
"url": "/datatables-json/advisory-committee-materials-json",
//"url": "/sites/default/files/actest1.json",
"dataSrc": ""
},
processing: true,
columns: [
{ "data": "field_publish_date" }, // publish_date 0
{ "data": "title" }, // node title summary 1
{ "data": "field_site_structure" } // site_structure Committee/Topic 2
],
columnDefs: [
{
"type": "date",
"targets": [ 0 ]
}
],
pageLength: 10,
searching: true,
autoWidth: false,
responsive: true,
lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
buttons: [
{
extend: 'excel',
text: 'Export Excel',
exportOptions: {
columns: [ 0, 1, 2 ]
}
}
],
initComplete: pageClass,
drawCallback: pageClass
}); // end datatable
// config and initialize filters
let select2config = {
maximumSelectionLength: 0,
minimumInputLength: 0,
tags: true,
selectOnClose: true,
theme: "bootstrap",
}
let search = $( '#lcds-datatable-filter--search' ).lcdsTableFilter({
table: otable9,
type: 'search'
});
let clear = $( '#lcds-datatable-filter--clear' ).lcdsTableFilter({
table: otable9,
type: 'clear'
});
// wait for ajax call to complete to load column data load
$('table.lcds-datatable--advisory-committee-materials').on( 'init.dt', function() {
let committee = $( '#lcds-datatable-filter--committee-topic' ).lcdsTableFilter({
column: 2,
table: otable9,
select2Options: select2config,
type: 'select',
dataType: 'datatable'
});
})
}}); // end ready function and condition if the table class exists.
I was able to pass in a function to alter the output of JSON so now the filter displays “Animal & Veterinary” not “Animal & Veterinary” By adding this below. The filter now displays Animal & Veterinary but selecting this in the filter does not match the value in the datatable?
let select2config = {
maximumSelectionLength: 0,
minimumInputLength: 0,
tags: true,
selectOnClose: true,
theme: "bootstrap",
escapeMarkup: function (text) { return text; }
}

jQuery datatable retain row highlight after reload

I am reloading my datatable on 10 second intervals. When a user clicks on a row, that row will highlight. But when the datatable reloads, the highlight is gone.
Here is the shortened code for my datable:
$(document).ready(function()
{
// set datatable
$('#example1').DataTable({
"ajax": {
"url": "api/process.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 600,
"scrollX": true,
"bDestroy": true,
"stateSave": true
});
// reload datatable every 30 seconds
setInterval(function()
{
var table = $('#example1').DataTable();
table.ajax.reload();
}, 30000);
// highlight row
$('#example1 tbody').on('click', 'tr', function()
{
$('#example1 tbody > tr').removeClass('selected');
$(this).addClass('selected');
});
});
All of the above works exactly how it's supposed to work. I just need to retain the row highlight after the datatable reloads.
Also, I attempted the answer from this post, but I scrapped it as the row no longer highlights.
Kindly update js file with below changes. Below code will save row clicked in global parameter and then focus the clicked row after ajax call.
var gblIndex = 0; //this will save row clicked index
function setFocus(){
$($('#example1 tbody > tr')[gblIndex]).addClass('selected');
}
$(document).ready(function()
{
// set datatable
$('#example1').DataTable({
"ajax": {
"url": "api/process.php",
"type": "POST",
"dataSrc": ''
},
"columns": [
{ "data": "" },
{ "data": "column1" },
{ "data": "column2" },
{ "data": "column3" }
],
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"scrollY": 600,
"scrollX": true,
"bDestroy": true,
"stateSave": true
});
// reload datatable every 30 seconds
setInterval(function()
{
var table = $('#example1').DataTable();
table.ajax.reload();
setFocus(); // this will set focus/highlight row
}, 30000);
// highlight row
$('#example1 tbody').on('click', 'tr', function()
{
$('#example1 tbody > tr').removeClass('selected');
$(this).addClass('selected');
gblIndex = $(this).index(); // this will save the index clicked
});
});
You should review their actual selection documentation to manipulate this. This feature is already built in and setup so on ajax.reload() it will keep your selections.
You can apply classes/styling with their methods as well.
https://datatables.net/reference/option/#select

DataTables ajax.reload when keeping pagination it jumps to the bottom of the page

I'm using jQuery DataTables with ajax sourced data.
I have to keep the data up to date every 30 seconds without refreshing the page, and ajax.reload() is the function that I need.
I put ajax.reload() inside a setInterval function.
And all works right (if you stay on page 1). But when you surf the table on page 2 or 3, when setInterval is fired, it gets you back to the page 1.
So ...
Looking to docs at this url: http://datatables.net/reference/api/ajax.reload()
if I pass "false" as second parameter it holds the current paging position, and paging is not reset on reload. BINGO!
It works! BUT ... I have a new problem that a tried to solve the all day and now I'm stuck. That's why I post this question.
It keeps paging but if you are not on page 1, every time that ajax.reload() is fired, the page scrolls (jump directly) to the bottom.
It's very unfriendly, unreadable, unusable.
I don't know WHY the page scrolls to the end-bottom.
I post a link to my simple datatable js that I use on my page.
jsfiddle
var url = table.data('url');
var filterType = table.data('filtertype');
var options = {
"ajax": {
"url": url,
"type": "GET",
"data": function (d) {
d.contact_type = filterType
// this variable will set by server when page load. It should be "lead", "prospect", "client". Leave empty to get all.
}
},
"columns": [
{"data": "html_is_company"},
{"data": "name"},
{"data": "html_type_label"},
{"data": "created"},
{"data": "last_update"},
{"data": "html_actions"},
{"data": "tsu"},
{"data": "business_name"}
],
"bLengthChange": false,
"pageLength": 20,
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"columnDefs": [
{
"targets": [ 7 ],
"visible": false,
"searchable": true,
},
{
"targets": [ 6, 7 ],
"searchable": false,
"visible": false
},
{
"targets": [0, 5],
"searchable": false,
"orderable": false
},
{
"targets": [ 4 ],
"render": function (data, type, row) {
return moment(data, IN_DATE_TIME_FORMAT, 'it').fromNow();//.format(DATE_TIME_FORMAT);////;
}
},
{
// Sort column 4 (formatted date) by column 6 (hidden seconds)
"orderData":[ 6 ],
"targets": [ 4 ]
}],
"order": [[4, "desc"]],
"search": "_INPUT_",
"language": {
"sSearchPlaceholder": "Cerca...",
"paginate": {
"previous": '<i class="icon wb-chevron-left-mini"></i>',
"next": '<i class="icon wb-chevron-right-mini"></i>'
},
//"url": "//cdn.datatables.net/plug-ins/1.10.9/i18n/Italian.json"
}
};
var datatable = table.DataTable(options);
this.setDataTable(datatable);
setInterval(function(){
datatable.ajax.reload(null, false);
}, 5000);
My solution:
"fnDrawCallback": function(data) {
$(".paginate_button > a").on("focus", function() {
$(this).blur();
});
}
jacopo.galli's solution was very clunky when I implemented for my table, but it's probably because my code was a mess. The idea of adding blur() is great thou.
I rewrite his code a bit:
$(window).scroll(function(){
$(".paginate_button > a").blur();
});
The buttons on the pagination bar will be "unfocused" once the page scrolls.
So your final code should look like this:
var url = table.data('url');
var filterType = table.data('filtertype');
var options = {
"ajax": {
"url": url,
"type": "GET",
"data": function (d) {
d.contact_type = filterType
// this variable will set by server when page load. It should be "lead", "prospect", "client". Leave empty to get all.
}
},
"columns": [
{"data": "html_is_company"},
{"data": "name"},
{"data": "html_type_label"},
{"data": "created"},
{"data": "last_update"},
{"data": "html_actions"},
{"data": "tsu"},
{"data": "business_name"}
],
"bLengthChange": false,
"pageLength": 20,
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"columnDefs": [
{
"targets": [ 7 ],
"visible": false,
"searchable": true,
},
{
"targets": [ 6, 7 ],
"searchable": false,
"visible": false
},
{
"targets": [0, 5],
"searchable": false,
"orderable": false
},
{
"targets": [ 4 ],
"render": function (data, type, row) {
return moment(data, IN_DATE_TIME_FORMAT, 'it').fromNow();//.format(DATE_TIME_FORMAT);////;
}
},
{
// Sort column 4 (formatted date) by column 6 (hidden seconds)
"orderData":[ 6 ],
"targets": [ 4 ]
}],
"order": [[4, "desc"]],
"search": "_INPUT_",
"language": {
"sSearchPlaceholder": "Cerca...",
"paginate": {
"previous": '<i class="icon wb-chevron-left-mini"></i>',
"next": '<i class="icon wb-chevron-right-mini"></i>'
},
//"url": "//cdn.datatables.net/plug-ins/1.10.9/i18n/Italian.json"
}
};
var datatable = table.DataTable(options);
this.setDataTable(datatable);
$(window).scroll(function(){
$(".paginate_button > a").blur();
});
setInterval(function(){
datatable.ajax.reload(null, false);
}, 5000);
I've found a solution that works for me.
The problem was the "focus" on DataTables pagination links.
When user clicks on a link page, it sets a focus on that link and when ajax.reload() is fired the browser gets you where the focused element is. My table is the last element of the page so the page scrolls to the bottom.
I got it when I clicked on another area of the page after clicked on page 2 link. The "jumping" problem was gone.
So, I solved firing a blur() when DataTables has complete its initialization and when ajax.reload() has finished (thanks to the first parameter that allows you to define a function).
In DataTables options I added this:
"initComplete": function(settings, json) {
$(".paginate_button > a").on("focus", function(){
$(this).blur();
});
},
and then, in setInterval:
setInterval(function(){
datatable.ajax.reload(function(){
$(".paginate_button > a").on("focus", function(){
$(this).blur();
});
}, false);
}, 30000);
Don't know if this is the "best solution" ... but it works and could helps someone.

How to manually delimit the number of displayed tows of a table (DataTables)?

Is there any possibility to manually delimit the numbers of the displayed rows of a (Data)Table?
Normally we use filtering input, but then the values are fixed; for example: 10, 25, 50, 100, All.
I would like to have a text field where I could insert the number of rows I wish to display; for example: 3, 7, 29, etc and then after clicking a button we would display the "pages" of the table only with the inserted number of rows.
I read some tutorials and did some searches, but was unable to find anything about it.
Here the JavaScript of my table (but I don't think it helps):
$('#search-table').dataTable({
"dom": "<'box-content'<'col-md-4'l><'col-md-8 text-right'f><'clearfix'>>rt<'box-content'<'col-md-5'i><'col-md-7 text-right'p><'clearfix'>>",
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ 8, 9, 10 ] }
],
"aLengthMenu": [[50, 100, 500, -1], [50, 100, 500, "All"]],
"iDisplayLength": 50,
"pagingType": "full_numbers",
"oLanguage": {
"sSearch": 'Filter within results: ',
"sLengthMenu": '_MENU_'
},
});
Any help is welcome!
Straight from datatable forums.
var oTable;
$(document).ready(function() {
$('YourButtonIdorSelector').click( function () {
var newDisplayLength = $("TextFieldIDOrSelectorHere").val();
var oSettings = oTable.fnSettings();
oSettings._iDisplayLength = newDisplayLength;
oTable.fnDraw();
});
oTable = $('#search-table').dataTable({
"dom": "<'box-content'<'col-md-4'l><'col-md-8 text-right'f><'clearfix'>>rt<'box-content'<'col-md-5'i><'col-md-7 text-right'p><'clearfix'>>",
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ 8, 9, 10 ] }
],
"aLengthMenu": [[50, 100, 500, -1], [50, 100, 500, "All"]],
"iDisplayLength": 50,
"pagingType": "full_numbers",
"oLanguage": {
"sSearch": 'Filter within results: ',
"sLengthMenu": '_MENU_'
},
});
});
or
var searchTable = $('#search-table').dataTable({
"dom": "<'box-content'<'col-md-4'l><'col-md-8 text-right'f><'clearfix'>>rt<'box-content'<'col-md-5'i><'col-md-7 text-right'p><'clearfix'>>",
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ 8, 9, 10 ] }
],
"aLengthMenu": [[50, 100, 500, -1], [50, 100, 500, "All"]],
"iDisplayLength": 50,
"pagingType": "full_numbers",
"oLanguage": {
"sSearch": 'Filter within results: ',
"sLengthMenu": '_MENU_'
},
});
searchTable.fnSettings()._iDisplayLength = $("TextFieldIDOrSelectorHere").val();
searchTable.fnDraw(); //redraw the table
You can simply add the new length you want displayed to the _iDisplayLength property and redraw the table.
When creating the data table, this stuff would go in the complete callback function fnInitComplete
$('#search-table').dataTable({
"fnInitComplete": function(oSettings,json){
var $table = this;
//example of how many rows to show
var newLength = 29;
//add the new value to your datatable object
oSettings._iDisplayLength = newLength;
//redraw the table, you have to do this to see the changes
$table.fnDraw();
},
//the rest of your settings
});

How to reinitialize jquery Datatable

How to reinitialize a jQuery datatable? I even tried to remove table element. Still that table is displaying. My code is like this:
function removeExistingDataTableReference(tableid)
{
if(oTable !=null)
{
oTable.fnDestroy();
}
if(document.getElementById(tableid)){
document.getElementById(tableid).innerHTML="";
}
oTable=null;
try
{
if(oTable !=null)
{
//oTable.fnDestroy();
alert("error in fndestroy");
}
oTable=null;
if(document.getElementById(tableid)){
document.getElementById(tableid).innerHTML="";
}
if(document.getElementById("FTable"))
{
removeElement(document.getElementById("FTable"));
}
}
catch(e)
{
alert("Error happend:"+e.message);
}
}
function removeElement(element)
{
try
{
var elem = document.getElementById('FTable');
elem.parentNode.removeChild(elem);
//ert(element.parentNode.id);
//element.parentNode.removeChild(element);
alert("removed");
return true;
}
catch(e)
{
alert(e.message);
}
return false;
}
How can I do that? After Search button click table is loaded. Again, when I search with another search parameter, table should load with new data. That is not happening. How to fix it??
Table is initialized like this:
function createDataTable()
{
try
{
oTable = $('#FTable').dataTable( {
"bDestroy":true,
"bJQueryUI": true,
"sScrollX": "100%",
"sScrollXInner": tablewidth+"px",
"bScrollCollapse": true,
"bSort":false,
"iDisplayLength" : 50,
"sPaginationType" : "full_numbers",
"aLengthMenu": [[10, 18, 50, -1], [10, 18, 50, "All"]]
} );
new FixedColumns( oTable, {
"iLeftColumns": 1,
"iRightColumns": 1
} );
}
catch (e)
{
alert(e.message);
}
}
You can reinitialize the datatable by clearing it and then adding the element using fnAddData().
First check whether the dataTable exists or not. The function fnClearTable() will clear the data from table.
In the code, dataTable is datatable variable and results is the id of table.
if(typeof dataTable === 'undefined'){
dataTable = $('#results').dataTable({
"aLengthMenu": [
[25, 50, 100, 200],
[25, 50, 100, 200]
],
"iDisplayLength" : 25,
"sPaginationType": "full_numbers",
});
}else dataTable.fnClearTable();
Then again add the data using fnAddData.
dataTable.fnAddData( [key, assignee, summary, status, days]);
You may use fnReloadAjax
http://datatables.net/forums/discussion/256/fnreloadajax/p1
oTable = $('#FTable').dataTable( {
"bDestroy":true,
"bJQueryUI": true,
"sScrollX": "100%",
"sScrollXInner": tablewidth+"px",
"bScrollCollapse": true,
"bSort":false,
"iDisplayLength" : 50,
"sPaginationType" : "full_numbers",
"aLengthMenu": [[10, 18, 50, -1], [10, 18, 50, "All"]]
} );
function reinit(){
oTable.fnReloadAjax( 'media/examples_support/json_source2.txt' );
}

Categories