I am having a few problems working with DataTable jQuery plug-in in my project. There are more than 20 tables using DataTable. Below is the javascript placed on every page that are using table with DataTable.
$(document).ready(function() {
pageSetUp();
var responsiveHelper_datatable_fixed_column = undefined;
var breakpointDefinition = {
tablet : 1024,
phone : 480
};
var otable = $('#datatable_fixed_column_GroupEnquiry').DataTable({
"stateSave": true, // saves state using localStorage
"sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6 hidden-xs'f><'col-sm-6 col-xs-12'<'toolbar'>>r>"+
"t"+
"<'dt-toolbar-footer'<'col-xs-12 col-sm-6 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
"autoWidth" : true,
"oLanguage": {
"sSearch": '<span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span>'
},
"preDrawCallback" : function() {
// Initialize the responsive datatables helper once.
if (!responsiveHelper_datatable_fixed_column) {
responsiveHelper_datatable_fixed_column = new ResponsiveDatatablesHelper($('#datatable_fixed_column_GroupEnquiry'), breakpointDefinition);
}
},
"rowCallback" : function(nRow) {
responsiveHelper_datatable_fixed_column.createExpandIcon(nRow);
},
"drawCallback" : function(oSettings) {
responsiveHelper_datatable_fixed_column.respond();
}
});
otable.state.clear(); //to clear saveState, but only work if the page is load for the second time
// Apply the filter
$("#datatable_fixed_column_GroupEnquiry thead th input[type=text]").on( 'keyup change', function () {
otable
.column( $(this).parent().index()+':visible' )
.search( this.value )
.draw();
} );
});
Situation
The tables work perfectly with saveState. When user go to specific page (example: page 5), and click on view detail (load new detail page), and click back button (load previous page with table) and the table still stays on the current page (page 5). This is what I want.
Problem
When user clicks on the navigation and redirect to the table, it still loads the table with previous state (which is in page 5) instead of display the 1st page and without any search filter.
Expected result
Supposed when user click on navigation and load table, the table should be display fresh state (on page 1 and without any search filter).
Attempt:
I placed otable.state.clear() as the code provided above, to clean the saveState of the table when user clicked navigation and display table. But it behaves weirdly, it only works on the second clicks on navigation.
I have no idea how actually saveState works and it is necessary to give unique id (#datatable_fixed_column_GroupEnquiry) for each table? I have more than 20 tables in different pages. How to clean saveState on specific button (navigation) and loads a fresh state table.
If anyone else searching for the solution, this helped for me.
I had the case that i wanted to clear the state when I access the dataTable with a link or pressed on refresh.
I put the followed piece of code, above the init of the dataTable inside the $(document).ready()
if (performance.navigation.type != 2){ //checks if page is accessed through a link or refresh
var table = $('#orderHistoryTable').DataTable();
table.state.clear();
table.destroy(); // need to destroy the table, I don't know why..
}
Related
I have an Angular project where I am using datatables but when I am browsing in the table and I am at the page 8 for example and I click another page and click back again to the table it's resetting the pagination and show me the page 1 instead of 8
Please how to fix that?
TS
allDestinations: any[] = [];
dtOptions: DataTables.Settings = {};
ngOnInit(): void {
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 25,
processing: true,
};
this._DestinationsService.destinations().subscribe((data) => {
this.allDestinations = data;
});
}
HTML
<table class="table table-bordered table-hover my-5" *ngIf="allDestinations.length > 0" datatable
[dtOptions]="dtOptions">
Can you add more code, like _DestinationsService code... ?
I don't know how you handle your pagination. But surely during your component initialization, it aks to get the first page of your data.
When you go on another page your component with the datable is destroy. And when you go back to your datable it is recreated and reinitialized.
One way to save the current page, it is to store the current page in your _DestinationsService, if it is a global service.
I have a DataTable with FixedHeader option that has the following initialization populated in my $(document).ready function. Both the headerOffset values that are jquery looked-up and hard-coded at 40 have been attempted, with the same results.
"fixedHeader": {
// "headerOffset": $("#top-navbar").outerHeight()
"headerOffset": 40
},
The DataTable is populated from an ajax call and has a series of my own render: functions on half of the columnDefs but I don't think that's related.
I'm not sure why, but the first time the page is loaded, the fixedHeader doesn't follow the top of the screen - but is sitting at the very bottom of the page below the table. When I click refresh - the header works just fine.
Any thoughts?
Thanks in advance.
I had the same problem, and in the absence of a satisfactory solution, my current workaround is to trigger a window resize event that will make the Datatable make rendering recalculations:
table.DataTable({
// ...
drawCallback: function() {
$(window).resize();
}
});
I have a Master detail jqGrid which is working perfectly. The detail grid is being populated based on a cellvalue from the Master grid's selected row and an ajax call to an API i.e. datatype: 'json' and url: 'http://myServiceurl/rowdata.id'.
However, for certain Master rows the data set for the detail row so it's taking a few moments to load and the detail grid shows "Loading...". This is perfectly fine, until the user clicks a different row in the master grid while the detail grid is still "Loading...". This is a problem because I am loading some additional info on the detail grid's caption and while the data on the detail grid is still loading from previous rowSelect the detail grid's caption changes to reflect the current master grid's row selected but the actual table data is from the previous row selected in the master grid.
The master-detail grid is coded as below jqgrid option on the master grid-
onSelectRow: function(ids) { //load the detail table tabDiv2
$("#"+divToHide).show(); //show the hidden div for detail grid
var rowdata = jQuery("#"+tabDiv).getRowData(ids);
jQuery("#"+tabDiv2).jqGrid('setGridParam',{url:useruri+"/"+rowdata.dbsid,
datatype: 'json'})
jQuery("#"+tabDiv2).jqGrid('setCaption',"Database Name: "+rowdata.dbname)
.trigger('reloadGrid');
},
One solution I could imagine is using beforeSelectRow option on the master grid and check if the detail grid is still being loaded-
beforeSelectRow: function(){
//check if detail grid is fully loaded <--
//if fully loaded return true else return false
}
How do I check if the detail grid is fully loaded? I have tried $("#"+tabDiv2)[0].grid but it always returns true since I think the overall DOM element of the grid gets loaded before the data gets loaded inside of it. I have tried checking number of records using $("#"+tabDiv2).getGridParam("records") but this may not always work, since the detail grid not having any row for a selected master grid row is a valid scenario and will permanently disable rowSelect on the master grid. What else are my options?
jqGrid set $("#"+tabDiv2)[0].grid.hDiv.loading to true during Ajax request to load the grid is pending. Then you can use just the following callback in the first grid
beforeSelectRow: function () {
var detailGrid = $("#"+tabDiv2)[0];
return detailGrid != null && detailGrid.grid != null && detailGrid.grid.hDiv.loading ?
false : true;
}
Solved it using the code below. However, based on my question on how to do it using beforeSelectRow, I prefer #Oleg's answer better. But just in case, below is another way of doing it.
By setting setgridparam on master grid beforeRequest and loadcomplete of detail grid.
onSelectRow: function(ids) { //load the detail table tabDiv2
$("#"+divToHide).show(); //show the hidden div for detail grid
var rowdata = jQuery("#"+tabDiv).getRowData(ids);
jQuery("#"+tabDiv2).jqGrid('setGridParam',{url:useruri+"/"+rowdata.dbsid,
datatype: 'json',
beforeRequest: function(){
jQuery("#"+tabDiv).jqGrid('setGridParam',{
beforeSelectRow: function(){
return false;
}
})
},
loadComplete:function(){
jQuery("#"+tabDiv).jqGrid('setGridParam',{
beforeSelectRow: function(){
return true;
}
})
}
})
jQuery("#"+tabDiv2).jqGrid('setCaption',"Database Name: "+rowdata.dbname)
.trigger('reloadGrid');
}
I need to highlight multiple words inside datatables https://datatables.net/.
Currently, my script highlights words on the first page of the table. Words on the second page are not highlighted when you go to that page first time. But they are highlighted if you go to another page and then get back to the second page once again. And so on. I know, the words on the second page are not highlighted first time because the pagination event callback function called asynchronously. How to highlight words from the hilitWrdArray[] array on the pagination event?
$(document).ready(function() {
var table = $('#example').DataTable( {
searchHighlight: true
} );
new $.fn.dataTable.FixedHeader( table, {
alwaysCloneTop: true
});
var hilitWrdArray = ["junior", "software", "chief", "regional", "specialist"];
var myHilitor = new Hilitor('#example');
myHilitor.apply(hilitWrdArray.join());
$('#example').on('page.dt', function () {
myHilitor.apply(hilitWrdArray.join());
}.bind(null, myHilitor, hilitWrdArray));
} );
Here is full code example:
http://jsfiddle.net/sergibondarenko/emp5gp6o/12/
mark.js is a text highlighter compatible with DataTables. Have a look at these two examples:
https://jsfiddle.net/julmot/buh9h2r8/
https://jsfiddle.net/julmot/c2am6zfr/
Usage is as simple as:
$(function() {
// Initialize DataTables
var table = $('.datatables-table').DataTable({});
// Initialize mark.js on table "draw" (search)
table.on('draw', function() {
// Get context
var tableContent = $(table.table().body());
// Specify keyword
var keyword = ["junior", "software", "chief", "regional", "specialist"];
// Remove previous marks
tableContent.unmark();
// Mark the new search keyword
tableContent.mark(keyword);
});
});
This initializes mark.js on table "draw", which includes the pagination event.
You can also keep track on this issue regarding a DataTables plugin for mark.js.
Update js fiddle try this if helpful for you. //jsfiddle.net/emp5gp6o/14/
I am using Jquery UI tab plugin.
Here is my DEMO
In my code I use
var tabControl = $("#tabs");
tabControl.tabs();
tabControl.tabs({ heightStyle: "auto",
beforeLoad: function (event, ui) {
},
load: function (event, ui) {
alert(ui.panel.selector);
if (ui.panel.selector == "#ui-tabs-1") {
m1();
} else if (ui.panel.selector == "#ui-tabs-2") {
m2();
}
}
});
When I moved to page 1st time it displays ui-tabs-1 correctly on pop up. But when I moved to some other page and come back and select the tab it shows an increased index (ui-tabs-4) and my desired method is not called. I don't know why my tab index gets increased. Your help is really appreciated.
Edit 1:
Thanks Rahul for creating the Demo. This code is part of a web application. This is related to one single page. In other pages also there are tabs. When I first load the page alert(ui.panel.selector) shows as "#ui-tabs-1" and when I go to other pages and come back it shows increased id such as #ui-tabs-4". I found that in the source code (jquery.ui.tabs.js) I found following implementation.
var tabId = 0,
rhash = /#.*$/;
function getNextTabId() {
return ++tabId;
}
Seems like tabId is increased and not being reset # . I want to reset that # every page load. Thank you very much for concerns.
Edit 2:
I have created a demo. when tabs clicked u get #ui-id-3 and #ui-id-5. In my scenario when I go back and come to the same page it displays as some increased number like #ui-id-7 for which it displayed #ui-id-3 previously.
Thank You!