I have following js function:
function addDatatable(orderArray) {
$('.Table').dataTable({
"order": [[ 3, "desc" ]],
dom: 'Blfrtip',
"columnDefs": [ {
"targets": 'no-sort',
"orderable": false,
} ],
...
I call this function on many jsp files, but on every page I would like to have another ordering. How I can send into the function specific order?
You could use data-* attributes for each table to define ordering if there are multiple tables and their configuration is the same besides ordering.
<table id="example" class="display" data-order="[[ 3, "desc" ]]" width="100%">
See this example for code and demonstration.
Related
I write Django app, where I have a base.html template and I defined var table where I declared order by column 0 with 'desc' (look below) So I currently use it some templates, where I extend base.html. But now I need to sort in new template firstly by the second column, and after that by the first column (like this: "order": [1, 0, 'desc'] ). I don't know how I modify this variable without a duplicate code. Could somebody help me?
var table = $('#example').dataTable( {
"columnDefs": [ {
"targets": 0,
"searchable": false,
"order": [0, 'desc'],
"ordering": true,
} ]
} );
In template which extends 'base.html'
<script>
//modify order method
</script>
You can set the ordering using .order() then redraw the table:
table.order( [ 1, 'desc' ], [ 0, 'desc' ] ).draw();
I have seen where others have asked this question (like here: Add child row as nested datatable within exisiting datatable) but I have yet to see it answered.
I have a "master" datatable that makes use of the child row feature. Here's the code that initializes the "master" datatable. (I'm including it just to be thorough, but everything here works perfect.)
var table = $('#members');
var oTable = table.dataTable({
"language": {
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
},
"emptyTable": "No data available in table",
"info": "Showing _START_ to _END_ of _TOTAL_ entries",
"infoEmpty": "No entries found",
"infoFiltered": "(filtered1 from _MAX_ total entries)",
"lengthMenu": "_MENU_ entries",
"search": "Search:",
"zeroRecords": "Loading..."
},
"buttons": [],
"columnDefs": [
{className: 'control'},
{orderable: false, targets: 0 }
],
// setup responsive extension: http://datatables.net/extensions/responsive/
"responsive": true,
"order": [
[1, 'asc']
],
"order-column": false,
"lengthMenu": [
[5, 10, 15, 20, -1],
[5, 10, 15, 20, "All"] // change per page values here
],
// set the initial value
"pageLength": 5,
"dom": "<'row' <'col-md-12'B>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
});
This next bit of code is located right after the above code and accomplishes 2 things:
1) It prevents multiple child rows from being opened at once (just a personal preference) and
2) Uses an AJAX call to populate the child row that was just toggled open.
table.on('click', 'tr', function () {
var id = $(this).attr('id');
if($(this).hasClass('parent'))
{
table.$('tr.parent').not(this).find('td:first-child').trigger('click');
var load_member_leads = $(this).next().find('td.child > ul > li span.dtr-data');
//var load_member_leads = $('#test');
$.ajax({
url: base_url + 'process/load_member_leads',
type: 'POST',
data: {test:id},
dataType: "html",
success: function(data){
console.log ("success");
load_member_leads.html(data);
formRepeater();
initTable1(id);
},
failure: function (data) {
console.log ("failed");
}
});
}
});
This portion of the code appears to be working well, but here is where it gets tricky. Within the returned AJAX data, I have an html table that I would like to initialize using the datatables plugin. Essentially what I'd have is a nested datatable within a child row of another "master" datatable. The problem is, everything works great until I try to initialize the datatable plugin on the nested table using:
initTable1(id);
(Note: the id variable being passed is to prevent multiple tables with the same ids. You can see in the code below how it's appended to the datatable init call.) Once this function is called, everything in the child row disappears and is erased from the DOM. Just gone. And I have no idea why.
Here is the code within the initTable1() function that initializes the 2nd datatable:
var table2 = $('#leads_' + id);
var oTable2 = table2.dataTable({
"language": {
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
},
"emptyTable": "No data available in table",
"info": "Showing _START_ to _END_ of _TOTAL_ entries",
"infoEmpty": "No entries found",
"infoFiltered": "(filtered1 from _MAX_ total entries)",
"lengthMenu": "_MENU_ entries",
"search": "Search:",
"zeroRecords": "No matching records found"
},
destroy: true,
//setup buttons extentension: http://datatables.net/extensions/buttons/
buttons: [],
// setup responsive extension: http://datatables.net/extensions/responsive/
responsive: {
details: {
type: 'column',
target: -1
}
},
"columnDefs": [ {
className: 'control',
orderable: false,
targets: -1
} ],
"order": [
[0, 'asc']
],
"ordering": false,
"lengthMenu": [
[5, 10, 15, 20, -1],
[5, 10, 15, 20, "All"] // change per page values here
],
// set the initial value
"pageLength": 10,
"dom": ""
});
And for good measure, here is the code being fetched by the AJAX call. (Note the $test variable is the same as the id variable being passed to the initTable1 function)
<table class="table table-striped table-bordered dt-responsive" width="100%" id="leads_<?php echo $test; ?>">
<thead>
<tr>
<th class="all">Column 1</th>
<th class="all">Column 2</th>
<th class="all">Column 3e</th>
<th class="all">Column 4</th>
<th class="all">Column 5</th>
<th class="all">Column 6</th>
<th class="all">Column 7e</th>
<th class="all">Column 8</th>
<th class="none">Column 9</th>
<th class="all">Column 10</th>
</tr>
</thead>
<tbody>
<!-- table rows populated here - this is currently hardcoded for testing -->
</tbody>
</table>
Here's what DOES work, which may shed some light as to what's actually causing the problem.
1) It works if I comment out the initTable1() function within the AJAX call...well everything but the initialization of the datatable plugin on the 2nd table. But the html populates where it should within the child row of the "master" datatable.
2) It works if I change where the AJAX data is being populated - specifically, it works outside of the "master" datatable. It not only populates where it should (note the commented out var load_member_leads that points to $('#test').), but it initializes datatables correctly as well.
It only seems to break if I both initialize datatables on the second table, and place said table in the child row of the "master" datatable. And by break, I mean completely disappear as if the AJAX call failed - which it isn't according to the console.log.
This problem is driving me crazy, what am I doing wrong? Any help is much appreciated!
I feel kind of stupid after spending hours on this one issue, but it turns out I was using the responsive extension rather than the built in functionality with datatables. For anyone else running into this issue, just follow and modify the code as needed from the example here: https://datatables.net/examples/api/row_details.html
I have a jQuery datable pluged into my ASP.NET application and currently, in order to show the column names, I have the following piece of code in my Razor view..
<table id="myDataTable" class="display">
<thead>
<tr>
<th>Contact name</th>
<th>Title</th>
<th>Country</th>
<th>City</th>
<th>Project</th>
</tr>
</thead>
<tbody style="font-size:x-small"></tbody>
</table>
Then, I have my javascript for the jQuery datatbles...
$('#myDataTable').DataTable({
"bServerSide": false,
"sAjaxSource": //controller binding,
"bAutoWidth": false,
"bProcessing": true,
"aoColumns": [
{ "sName": "CONTACT_NAME" },
{ "sName": "TITLE"},
{ "sName": "COUNTRY" },
{ "sName": "CITY" },
{ "sName": "PROJECT" },
],
"bDestroy":true
});
However, when I render the HTML the first time before I fill in the table, it looks awkward because I am rending some random HTML (that is related to the future column names) with no datatable at all...
How can I define the column of my table without having to set it in the HTML so I can avoid having that random text there?
Thanks!
just set the initial CSS of the #myDataTable to visibility:hidden; like this:
#myDataTable { visibility:hidden; }
That way you can put it right in the HTML and just call the following JavaScript to show it after you update the values:
document.getElementById('#myDataTable').style.visibility = "visible";
I am aware that thanks to fnReloadAjax or combination of fnClearTable() and fnAddData() I can reload some fresh data
but is it possible this way somehow to redefine settings of table, in particulary: columns names, which are hidden, which are visible?
UPDATE:
If you will decide for destroying the table the easier way as checking existence and destroying like this:
if $.fn.DataTable.isDataTable("#element") {
$('#element').DataTable().destroy();
}
can be just setting the property in DataTable definition: bDestroy: true
I think you can redfine the settings by destroying the dataTable altogether like:
//part1
$( "#element" ).dataTable({
"sPaginationType": "full_numbers",
"iDisplayLength": 25,
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0 ] } //cannot sort using column 1
]
});
----------
//part2
$( "#element" ).dataTable().fnDestroy();
$('#element').dataTable( {
"aoColumnDefs": [
{ "bVisible": false, "aTargets": [2] } //hiding the column 3
]
} );
Here I just destroyed the dataTable for no reason but you can link it with some event.
i'm currently using Datatables for a Custom system and i would like to disable Sort for every column but the first one.
I tried with the following code wich is working fine when i add values separated by comma
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ 1, 2, 3, 4 ] }
],
But my tables column number vary for each individual file so i can have 3 or maybe 12 columns, and i don't want to have to manually add the values for each file.
If i add more values than the columns i have in one file i get the following error, and an execution stop
Uncaught TypeError: Cannot read property 'className' of undefined
So, is there any way i can get those index and pass them to the function?
Thanks!
You can add a specific class to the TH element that you do not want to be sortable.
<table>
<thead>
<th>
...
</th>
<th class="no-sort">
...
</th>
</thead>
<tbody>
...
</tbody>
</table>
And then you can specify this class in your aTargets parameter.
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': ['no-sort'] }
]
View here for more information on the Column specific options.
And then you can specify this class in your aTargets parameter.
columnDefs: [ { orderable: false, targets: [1,2,3,4,5,6,7,8,9] } ]
This worked for me and seems more practical (though not exactly elegant)
columnDefs: [
{
"targets": [0],
"orderable": true
}, {
"targets": [''],
"orderable": false
}
]