Can't destroy() jQuery Data Table - javascript

I am having an issue with trying to destroy a JQuery Data Table.
Here is where I initialize it:
$(document).ready(function() {
var table = $(".dynamic-wide-table").DataTable({
"aaSorting": [],
"scrollX": true,
"scrollY": 530,
"scrollCollapse": true,
"lengthMenu": [
[100, 400, 1000, 5000, -1],
[100, 400, 1000, 5000, "All"]
],
"retrieve": true
});
});
Here is where I try to destroy it:
$(document).ready(function() { // Note that my page has two tables on it!
table.destroy();
table[0].destroy();
}); // Trying to delete both tables first, then just the first table
Here are my errors:
Uncaught TypeError: table.destroy is not a function
Uncaught TypeError: table[0].destroy is not a function
Does anybody know what's going on?! I'm very confused.
Edit:
Here is an image of what happens when I console.log table.

Instantiate the tables with an each() loop and store them in an array:
$(document).ready(function() {
var tables = [];
$("table").each(function(i){
var table = $(this).DataTable({
"aaSorting": [],
"scrollX": true,
"scrollY": 530,
"scrollCollapse": true,
"lengthMenu": [
[100, 400, 1000, 5000, -1],
[100, 400, 1000, 5000, "All"]
],
"retrieve": true
});
tables.push(table);
});
$('#button').click( function () {
// Then you can call destroy on that object
var elem = tables[0].table().node();
tables[0].destroy();
// And empty the element
$(elem).empty()
} );
} );
Link to jsFiddle

You can't both create and destroy a DataTable within $(document).ready(), since those events are triggered at the same time. See #CMedina's JSfiddle where he shows that they work when triggered by, say, a button click. (Assuming these are in the same file) Ignore this part; apparently they are different files.
Note that you said in a comment that the creation/destroy are in different files. If that's indeed the case, how is the destroying file made aware of table? If it's not aware of the DataTable (which could also be caused by not including the script file on that page) then it won't know what destroy() does, and throw an error.
Edit: I just noticed that you are trying to use destroy() on table and then on table[0]. You can't have table be a DataTable and also an array of DataTables. Try naming your tables uniquely or both in arrays; either
var table;
table[0] = $('#example').DataTable();
table[1] = $('#example2').DataTable();
Or (probably better)
var table1 = $('#example').DataTable();
var table2 = $('#example').DataTable();

I suppose that you have 2 datatables in your page, and your initializacion is for all tables with the class .dynamic-wide-table.
For destroy only one table you should get all datatables in your page with tables function.
Then apply destroy to specified table: (In my example work with 2 datatables).
$(document).ready(function() {
var table = $(".dynamic-wide-table").DataTable({
"aaSorting": [],
"scrollX": true,
"scrollY": 530,
"scrollCollapse": true,
"lengthMenu": [
[100, 400, 1000, 5000, -1],
[100, 400, 1000, 5000, "All"]
],
"retrieve": true
});
$('#destroy1').click( function () {
var dt1 = $.fn.dataTable.tables()[0];
$(dt1).DataTable().destroy();
} );
$('#destroy2').click( function () {
var dt2 = $.fn.dataTable.tables()[1];
$(dt2).DataTable().destroy();
} );
} );
Result: https://jsfiddle.net/cmedina/7kfmyw6x/80/

I had same issue. although there was only one table in my page, but I'd got error:
Uncaught (in promise) TypeError: tbl.destroy is not a function
the reason for me was because instead of initializing dataTable like:
let tbl = $('#myTable').DataTable();
I'd wrote it as:
let tbl = $('#myTable').dataTable();
please notice to write .DataTable with capital D.

Related

how to dump all setting of handsontable instance and save to server(not save data in table to server)

I want to achieveļ¼š
One user creates handsontable using client browser: to insert or delete some columns, edit column headers, fix some rows or columns by context menu for other users to fill. So I need to save handsontable structure to server.
The following code initialize a 3*3 handsontable with contextMenu: true
var
$$ = function(id) {
return document.getElementById(id);
},
container = $$("example"),
hot;
Handsontable.dom.addEvent(createtable, "click", function() {
hot = new Handsontable(container, {
rowHeaders: true,
colHeaders: true,
dropdownMenu: true,
startRows: 3,
startCols: 3,
contextMenu: true,
licenseKey: 'non-commercial-and-evaluation',
})
})
Then I set column A readonly by context menu.
Using following code get columns option. I expect the result is [{readonly: true},{},{}], but it is undefined
Handsontable.dom.addEvent(gettablesetting, "click", function() {
console.log(hot.getSettings().columns)
})
how to dump all options of handsontable instance and save to server for other users to fill.
jsfiddle code

JavaScript Datatable.JS / PHP MySQLi Sorting Issue

So I'm using Datatables.JS to create a table of results returned from a MySQL database. When I return the results I'm trying to display them in DESC order. I have tried using ORDER BY DESC in my MySQLi query, this does return the results in the correct order, however when datatables is reading the results it's displaying them in some random order. So I've tried playing with the datatable settings to sort by my ID column but keep that column hidden. Whenever I attempt to add any code to handle the sorting, the sorting issue itself becomes resolved but all my pagination and buttons such as the buttons that allow the user to select which columns they would like to view just disappear. Below is the JS I'm using to select the features and setup I need for this datatable, can anyone show me how to add sorting by the ID column DESC into this without breaking it?
$(document).ready(function() {
$('#datatable').DataTable();
//Buttons examples
var table = $('#datatable-buttons').DataTable({
pageLength: 20,
lengthChange: false,
searching: false,
buttons: ['copy', 'excel', 'pdf', 'colvis']
});
table.buttons().container()
.appendTo('#datatable-buttons_wrapper .col-md-6:eq(0)');
} );
Adding ordering: and then selecting the column and defining the order seems to break all the other settings, I lose my pagination and default results length as well as all control buttons on the page.
$(document).ready(function() {
$('#datatable').DataTable();
//Buttons examples
var table = $('#datatable-buttons').DataTable({
pageLength: 20,
lengthChange: false,
searching: false,
buttons: ['copy', 'excel', 'pdf', 'colvis'],
order: [[ 1, desc ]]
});
table.buttons().container()
.appendTo('#datatable-buttons_wrapper .col-md-6:eq(0)');
} );
I have no idea why this solutions works and I still don't understand what caused the original problem but I did find a working piece of code posted under a loosely relevant problem on another forum. I combined that code with what I had already and it solved my problem. Hopefully this helps someone else out who may encounter the same issue.
$(document).ready(function() {
$('#datatable-buttons').DataTable( {
pageLength: 20,
lengthChange: false,
searching: false,
ordering: true,
order: [[ 3, 'DESC' ]],
dom: 'B1frtip',
buttons: [
'copy',
'excel',
'pdf',
'colvis'
]
});
table.buttons().container()
.appendTo('#datatable-buttons_wrapper .col-md-6:eq(0)');
});
Just wanted to mention this JS was for a datatable that's part of the Fonik Bootstrap Admin Template.

DataTables Javascript Library - Headers Not Lining Up - Data Shifting

I'm using the Datatables javascript library to display data.
When the search returns a lot of data, it seems to work okay.
If you stretch the window out far enough, it won't actually line up properly, but it's "usable" for the most part.
Unfortunately, when it doesn't return much data, the center data shifts as seen here:
I sort of managed to get it to work in the past by setting bAutoWidth to false, but then it broke the headers when more data was returned -_-
I've been fighting this for weeks, so any help would be appreciated.
Initialization code:
dtTable = $("#CompletedSitesTable").DataTable({
"scrollY": "50vh",
"scrollX": "auto",
"paging": true,
"pageLength": 100,
"bScrollCollapse": true,
"bAutoWidth": true,
"order": [[ 7, "asc" ]],
dom: "Bfrtip",
buttons: [
'copy', 'excel',
{
extend: 'pdfHtml5',
orientation: 'landscape',
}
]
});
Well I wasn't sure I would get much response from this, but what I did was completely hacky.
On fnInitComplete I simply check to see if the datatable has a scrollbar and, if not, I set the width of the div to the width of the headers.
I guess you would change #resultsDiv to whatever your wrapper div was and
Function to check for scroll bar:
(function($) {
$.fn.hasScrollBar = function() {
return this.get(0).scrollHeight > this.height();
}
})(jQuery);
The fnInitComplete code.
"fnInitComplete": function(oSettings, json) {
if(!$(".dataTables_scrollBody").hasScrollBar())
$("#resultsDiv").css({ "max-width": $(".dataTable").width()});
}
I guess this will get left like this for now - seems really dumb.

How to remove sorting on ui-grid before reload another data set ui-grid

Im using ui-grid to load my data set. Here is my requirment;
step 01: I want to load dataset_01 (scope.gridOptions.data = res_01;).
step 02: I want to sort by First Name (Click by firstname column).
step 03: Click an external button and Reload ui-grid with an another data set (scope.gridOptions.data = res_02;).
Here is my result:
I dont want sort by First Name here for second dataset.
I want data without sorting. How can I do it ?
Expected result:
So I want to reload second data set without sorting (Means I want to remove first sorting before load second data set). how can I reset my ui-grid before load next data set (scope.gridOptions.data = res_01;).
How can I do it ?
Thank you. :)
You can set the sort property of your columnDefs to:
sort: {
direction: undefined,
}
and call for grid refresh using $sope.gridApi.core.refresh() after. This should re-render the whole grid and get rid of the sorting.
Visit this page: http://ui-grid.info/docs/#/api/ui.grid.core.api:PublicApi
After having instantiated your gridApi, you can just call:
$scope.gridApi.core.refresh();
Hope that helps! :)
Create your gridoption like this
example
$scope.gridOptions = {
useExternalPagination: true,
useExternalSorting: false,
enableFiltering: false,
enableSorting: true,
enableRowSelection: false,
enableSelectAll: false,
enableGridMenu: true,
enableFullRowSelection: false,
enableRowSelection: false,
enableRowHeaderSelection: false,
paginationPageSize: 10,
enablePaginationControls: false,
enableRowHashing: false,
paginationCurrentPage:1,
columnDefs: [
{ name: "FristName", displayName: "Frist Name", width: '6%', sort: { direction: undefined } },
]
};
after that you can remove the sorting where you want using below code
$scope.RemoveSorting = function ()
{
$scope.gridOptions.columnDefs.forEach(function (d) {
d.sort.direction = undefined;
})
}

Two DataTable in One Page - Second one initialising weird

I have two dataTable in my page and I have a method like below:
function ToDataTable()
{
$(".dataTable").css("width", "100%");
$(".dataTable").each(function ()
{
var $that = $(this);
/* Start of method */
function ToDataTableInternal()
{
var table = $that.DataTable({
responsive: {
details: { type: "column", target: -1 },
},
columnDefs: [{
className: "control", orderable: !1, targets: -1,
},
{ orderable: !1 }],
"paging": false,
"ordering": false,
"info": false,
"searching": false,
retrieve: true
});
}
/* End of method */
if ($that.is(":visible"))
{
ToDataTableInternal()
}
else
{
// Observe all invisible parents or table to trigger
// ToDataTableInternal method if made visible
var $arr = $(this).parentsUntil(":visible").filter(function ()
{
return $(this).css("display") === "none";
}).add($(this));
var observers = [];
$arr.each(function ()
{
var observer = new MutationObserver(function (mutations)
{
mutations.forEach(function (mutation)
{
if ((mutation.attributeName === 'style' ||
mutation.attributeName === 'class') &&
$that.is(":visible"))
{
ToDataTableInternal();
for (var i = 0; i < observers.length; i++)
{
// Disconnect observers
observers[i].disconnect();
}
}
});
});
observers.push(observer);
observer.observe(this, {
attributes: true
});
});
}
});
}
The reason I have this method is that when table's display is none, it really lags browser(especially IE, where I cannot do anything for minimum of 5 seconds) which is the reason of that I'm changing the table to DataTable after it made visible.
But the problem with calling methods individually is the second DataTable doesn't have the same settings which I passed on.(The first one has) Instead, second one has filters, paging, sort elements in it too.
If I call both at the same time, nothing out of ordinary happens. What may be the problem?
EDIT: I can't reproduce the same behaviour in fiddles.
There seems to be no problems in another environments when I'm trying to do the same thing.
An another library we use is causing problems and there is no problem with DataTable library.
you can add following properties of dataTable in your datatable configuration to remove filtering, pageing and sorting:
Datatable 1.9
"bPaginate":false, //Enable or disable pagination.
"bFilter": false, //Enable or disable filtering of data
"bLengthChange": false, //Enable or disable the size dropdown
"bSort": false, //Enable or disable sorting of columns.
"bInfo": false, //Enable or disable the table information display.
Update
Datatable 1.10
Option name update in datatable 1.10
bPaginate -> paging
bFilter -> searching
bLengthChange -> lengthChange
bSort -> ordering
bInfo -> info

Categories