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.
Related
I am trying to add datatable info i.e "Page 1 of 1" between pagination text. Is it possible to achieve this?
var table = $('#example').DataTable({
pagingType: "full",
pageLength: 5,
info: true,
language: {
info: "Page _PAGE_ of _PAGES_",
paginate: {
previous: '<',
next: '>'
}
}
})
Add this to your code:
I edit my code to fit your case. Also it appears that datatable need to keep the original info element in order to do the update after you switch to another page, so you need to clone it to the new place instead of cut and paste, and set hide
drawCallback: function( settings ) {
$(".dataTables_paginate").children(':eq(1)').after($(".dataTables_info").hide().clone().css({'display':'inline-block', 'float': 'unset'}));
}
https://jsfiddle.net/96oy3buk/3/
I am new to data-tables and I am trying to do this but i wanted to do with pagination since the answer provided in the link did not involve any pagination. Is it possible? Because i have tried and when i set the pagination to true, the drop-down solution in the link given won't work.
<script type="text/javascript">
$(document).ready(function() {
$('#datatable-responsive').DataTable( {
"responsive": true,
"paging": true,
"dom": 't<"margin-dataTable-bottom"<"pull-left margin-dataTable-pagination">>'
} );
} );
</script>
You can try this alternative solution which is an extensible pagination mechanism in datatable,
$(document).ready(function() {
$('#example').DataTable( {
"pagingType": "full_numbers"
} );
} );
Please find below link for more details:
https://datatables.net/examples/basic_init/alt_pagination.html
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.
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;
})
}
I have two grids that have rows I can select. I want to be able to get the data in the selected rows into another data object so that I can pass it to a backend service. Here is the relevant code:
angular.module('gridPanel',['ui.bootstrap','ui.grid', 'ui.grid.edit', 'ui.grid.rowEdit', 'ui.grid.cellNav', 'ui.grid.selection'])
.controller('GridPanelController', function($scope, $log, referenceDataService){
$scope.nameGrid = {
enableRowSelection: true,
enableRowHeaderSelection: false,
multiSelect: true,
onRegisterApi: function(gridApi) {
$scope.gridApiNames= gridApi;
},
columnDefs: [
{name: 'Name', field: 'name'}
{name: 'Description', field: 'description'}
],
data:[]
};
$scope.regionsGrid = {
enableRowSelection: true,
enableRowHeaderSelection: false,
multiSelect: true,
onRegisterApi: function(gridApi) {
$scope.gridApiRegions = gridApi;
},
columnDefs: [
{name: 'Region', field: 'region'}
],
data:[]
};
referenceDataService.getAllNames().then(function (data){
$scope.nameGrid.data = data;
});
referenceDataService.getRegions().then(function (data){
$scope.regionsGrid.data = data;
});
$scope.debug = function(obj) {
var dataObj = {
names: [],
regions: []
};
dataObj.regions = $scope.gridApiRegions.selection.getSelectedRows();
dataObj.names= $scope.gridApiNames.selection.getSelectedRows();
$log.log(JSON.stringify(dataObj, null, 4));
};
});
However, when I check to see what the log says in console, it shows me that dataObj.regions and dataObj.names are both blank arrays. The data shows up fine in the actual tables, and nothing goes wrong when I click on them - I can select multiple rows without issue. The problem only comes when I click on the submit button, which for now directs to $scope.debug so that I can look at the objects in console. I have other fields in the form, mostly text fields, that also display fine when I click on debug in the console log, so the only place with an issue is getting selected rows. Thanks in advance!
edit: also, when I try to log just the 'getSelectedRows' part, it returns a blank array.
Found the problem. It's because I was using the same grids elsewhere on the webpage (within a modal) to display the same information. Once I made two sets of grids, the problem was fixed. Still seems kind of inefficient to have two sets of the same grids that serve the same purpose, but I guess maybe that's just how it is or something?