Sort table by a column with DataTables - javascript

I'm trying to sort a table by a particular column with DataTables, but I receive this warning:
DataTables warning: table id=DataTables_Table_0 - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
I put these scripts but maybe I'm doing something wrong:
jQuery('.sp-template-league-table table').DataTable({ paging: false, searching: false, info: false, retrieve: true });
jQuery('.sp-template-league-table table').DataTable().column('.data-tot').order('asc').draw();
You can see the table in this page: http://www.quartuleague.com/goldcup-2015-girone-gold/
under the "Fair Play" Tab, i want to sort table by "TOT"

If you want to sort the data by default you can also pass along additional parameters on the initialization instead of using .draw():
Example: Ascending sorting of the 4th column (indices start at 0)
$('#example_table').DataTable( {
"order": [[ 3, "asc" ]]
} );
In your case you need to add the column number of your data-tot column (8 or -1) like so:
jQuery('.sp-template-league-table table').DataTable({
order: [[ 8, "asc" ]],
paging: false,
searching: false,
info: false,
retrieve: true
});

Related

How to controll two datatable using one lengthMenu

I have two tables in the same View/Page. I am using jquery datatable and to target both the table, I have used .display in both tables.
Question: Both the table has separate tableLength dropdown, How to target both using the top dropdown?
In Layman term, since both table has separate dropdown, both works properly for respective table. I want to use first table's dropdown and If I select 25, it should select 25 for the bottom dropdown and both the tables should show 25 records.
What I tried: I have made customized dropdown (orange box) which will call onChange event and will get the value and pass that value to Datatables "aLengthMenu" and "iDisplayLength" keys.
Below screenshot is taken from the UI I am working, can't paste the full picture. "Show 5 entries" is the LengthMenu.
`
<html>
.
.
<table class="display" id="tbl_result1">
</table>
<table class="display" id="tbl_result">
</table>
.
.
</html>
$('table.display').DataTable({
"aaSorting": [],
'aoColumnDefs': [{
'bSortable': false,
'aTargets': ['col-action']
}],
"zeroRecords": "No",
"language": {
"zeroRecords": " ",
"infoEmpty": " ",
"searchPlaceholder": "Search for an issue"
},
"aLengthMenu": [[5, 10, 25, -1], [5, 10, 25, "All"]], //LeftArray:value,rightArray: UI Dropdown
"iDisplayLength": 5, // By default rows
"searching": false,
"bStateSave": true,
"bPaginate": true, // true/false to enable/disable Pagination
"bInfo": false, // true/false to enable/disable the "Showing 1 of N records" message
"ordering": false, // true/false to enable/disable table sorting
'columnDefs': [{ // For disabling sorting in a particular table columns
'targets': [0], // column index (start from 0)
'orderable': false, // set orderable false for selected columns
}],
"fnStateSave": function (oSettings, oData) {
localStorage.setItem('offersDataTables', JSON.stringify(oData));
},
"fnStateLoad": function (oSettings) {
return JSON.parse(localStorage.getItem('offersDataTables'));
},
"dom": '<"pull-left"f><"pull-right"l>tip'
});
`
Tried calling onChange event listner and passing the value from customized dropdown, called a function that passes the value as an argument (let say variable is newLengthVal)to the Datatables like
`
"aLengthMenu": [[newLengthVal], [newLengthVal]], //LeftArray:value,rightArray: UI Dropdown
"iDisplayLength": newLengthVal, // By default rows
`

How to hide index column of DataTable?

How can I hide the first column of my DataTable which contains indexes of my rows?
I already tried bSortClasses: false and orderClasses: false, but it didn't work.
Solved :
columnDefs: [
{ "visible": false, "targets": 0 }
],

Disabling ordering in jQuery DataTables stills loads with order icon

I have a 4 columns DataTable that needs ordering, except for first column. I tried using "columns": [ {"orderable": false}, null, null, null ], but the first column shows the ordering icon (caret) on page load.
When I order another column, the icon disappear from first column, but there is still the space where it was, breaking the column width. Is there any way to REALLY disable the ordering, in a way that it also doesn't add any special padding?
SOLVED:
#ShaktiPhartiyal answer fixed the sorting problems. The width problem was fixed by setting the autowidth option to false and using a little CSS.
CSS part
table.dataTable thead tr th:first-child,
table.dataTable tbody tr td:first-child {
width: 0px;
}
DataTables options
$(table).DataTable({
"paging": false,
"columnDefs" : [
{ targets: 0, sortable: false},
],
"order": [[ 3, "asc" ]],
"autoWidth": false
});
Even if you disable sorting for a column, the dataTables sort order still remain. By default order is [0, 'asc']; simply set order to target the #2 column instead :
var table = $('#example').DataTable({
//....
order: [[ 1, "asc" ]] //column indexes is zero based
});
Working Fiddle
To disable ordering / sorting in datatables you can use the following parameter:
"aoColumns": [{ "bSortable": false }, null],
The code tells datatable to disable sorting in the first column.

Jquery Datatable is not getting recreated

I am creating jquery Datatable dynamically. ColumnNames and Rows Values are coming from Server side using Ajax call. Now, I need this datatable to be reinitialized everytime, so I used property "bDestroy": true, on every ajax call but after first display, DOM is getting broken. Here is my code
$('#JDatadt').dataTable({
"order": [],
"dom": "Bfrtip",
"buttons": ["csv", "excel", "pdf"],
"columnDefs": [{ "className": "dt-center", "orderable": false, "width": 20 }],
"bInfo": false,
"paging": true,
"processing": true,
"bDestroy": true,
"columns": dataObject[0].columns,
"data": dataObject[0].data
});
What is getting wrong here. Please help
Datatable by default try to sort column with index 0 if not specified.
if you don't want to sort by default with any column just add
"aaSorting": [[ ]] ,
you can destroy table by using fnDestroy() function of datatable. it will surely works for you.

DataTable not showing pagination buttons and records info - JQuery

Using Datatable plugin for pagination, I can't get it to display pagination buttons and records information ("Showing X out of Y Records"). It is fetching the records correctly when I am selecting the page size from the drop down just above the table, but for some reason, it is not showing pagination buttons.
My guess is that it has to know the Total Record count of the table, and I am giving it that in the ""iTotalRecords": 10000" part, I have 1000 records in my table, but still it is of no use. What exactly am I missing here?
It is passing the start (page number) and length (page size) params correctly.
Below is my code,
$('#leadDetailTable').dataTable({
"processing": true,
"serverSide": true,
"info": true,
"stateSave": true,
"lengthMenu": [[10, 50, 100, 500], [10, 50, 100, 500]],
"iTotalRecords": 10000,
"iDisplayLength": 10,
"searching": false,
"scrollY": false,
"scrollX": false,
"ajax":{
type: 'POST',
url: '#Url.Action("SearchLeads", "ResourceManagement")',
data: args,
success: function (result) {
/* Do things with result */
},
}
});
Have you tried adding following parameters:
"bPaginate":true,
"sPaginationType":"full_numbers",
"bLengthChange": true,
"bInfo" : true
I had the same issue and it was because I returned the wrong recordsFiltered value from the server-side. Make sure that the recordsTotal value represents the number of records(rows) in the table and the recordsFiltered value represents the number of rows that should stay hidden of the total rows. DataTables uses this information to create the pagination buttons.
Add the below property
"pagingType": "full_numbers"
What is the response being returned by the ajax request? It should include the following:
{
data: <the array of row data>,
draw: <the same value the request had for its draw value>,
recordsTotal: <the total number of records>,
recordsFiltered: <the total number of records after filtering>
}
If you don't want it to say "filtered from x records", then count the records after filtering and set both recordsTotal and recordsFiltered to that value.

Categories

Resources