Set sort column using data attribute from table head - javascript

I'm using jQuery dataTable, and I want to define which columns to be sorted in the html, like this:
<table id="report">
<thead>
<tr>
<th data-order="false">Code</th>
<th data-order="true">Name</th>
</tr>
</thead>
In javascript initialization it iterate through the columns and set order parameter only ones with "data-order=true".
How can I do this?

I got this to work:
http://datatables.net/forums/discussion/12736/setting-sortable-with-aocolumndefs-glitched
in javascript:
var oOptions = {
aoColumnDefs: [
{aTargets: ['searchable'], bSearchable: true},
{aTargets: ['sortable'], bSortable: true},
{aTargets: ['_all'], bSortable: false, bSearchable: true}
]
};
$('#table_report').dataTable(oOptions);
in html use the class "sortable" in the column:
<th class="sortable">Header X</th>

Related

CSV export always only exports one row

I have a pretty simple datatables object. I bind it to an array of objects, specify the data fields and it works. The problem is when I try to implement the CSV export. It always only wants to export the first row of the table. Any ideas?
Here's where my code stands at the moment. And to be sure, I've made sure that the button and select libraries are included but that has made no difference.
<table id="tblData" style="display:none;">
<thead>
<tr id="trDataTableHeader">
<th data-s-type="string">Name</th>
<th data-s-type="string">Address</th>
<th data-s-type="string">Phone</th>
<th data-s-type="string">Website</th>
<th data-s-type="string">Types</th>
</tr>
</thead>
</table>
...
table = $('#tblData').DataTable({
dom: 'rtB',
data: tableData,
columns: [
{ "data": "name" },
{ "data": "address" },
{
"data": "phone_number",
defaultContent: ""
},
{
"data": "website",
defaultContent: ""
},
{
"data": "types",
defaultContent: ""
},
],
buttons: [{
extend: "csv",
text: "Export",
exportOptions: {
modifier: { search: "none", selected: false}
}
}],
select: false,
lengthChange: false,
sort: false,
paging: false
});
After a lot of digging, I made an accidental discovery when I removed the column data type specifications. I got an error message that str.replace is not a function.
Turns out that the parseInt and parseFloat base functions were being overridden by another developer on that page and was causing a problem but DataTables was too graceful to tell me.
This is why you don't override base javascript functions unless you absolutely have to.

jQuery datatables - how to set the column name

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";

How to disable sorting on specific column while searching is functional

I am using DataTable (http://www.datatables.net) in order to get desired functionality including sorting columns and searching within columns from Table Heading individually. Initializing is as follow which returns api and searching functionality is achieved.
$('#table2').DataTable()
Now Problem is when I have to disable sorting on checkbox and I have to use following line of code.
$('#table2').dataTable( {
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [ 0 ] }
] } );
it does apply sorting disabled on column but search functionality within column also doesn't work. Is there any way I can pass any parameter in DataTable({something}) in order to disable sorting on first column or please help me to combine (api & jquery object) method in order to achieve desired functionality.
$('#table2').DataTable();
$('#table2').dataTable();
<table class="table table-striped draggable sortable dataTable" id="table2">
<thead>
<tr>
<th class="text-center"> <input class="check_box_all no-sort" id="check_all" type="checkbox" title="Check All"></th>
<th class="text-center">Company Name </th>
</tr>
</thead>
<tbody>
<tr class="odd gradeX">
<td class="text-center"><input type="checkbox" class="check_box"></td>
<td class="text-center">Med Assets Company</td>
</tr>
</tbody>
This snippet makes input field in table heading for searching purpose
$('#table2 thead th').slice(3).each(function () {
var title = $('#table2 thead th').eq($(this).index()).text();
$(this).html('<input type="text" placeholder="' + title + '" />');
});
Data Table Initialize
var table = $('#table2').DataTable({
"dom": 'C<"clear">lfrtip',
"sPaginationType": "full_numbers",});
Applying the search
var tableResult = table.columns().eq(0);
if (tableResult !== null) {
tableResult.each(function (colIdx) {
$('input', table.column(colIdx).header()).on('keyup change', function () {
table
.column(colIdx)
.sort()
.search(this.value)
.draw();
});
});
}
Please check jsfiddle when check box is checked it totally mess up
https://jsfiddle.net/sxgd0thm/
$('#example').dataTable( {
"aoColumnDefs": [
{ "bSearchable": true, "aTargets": [ 0,1,2,3,4,5 ] }
] } );
Try with "bSearchable" with allowable column search
$('#table2').dataTable({
"dom": 'C<"clear">lfrtip',
"sPaginationType": "full_numbers",
"aoColumnDefs": [
{ "bSearchable": false, "aTargets": [ 0 ] },
{"bSortable": false, "aTargets": [ 1 ]}
]});
Can you try with this

Disable Sorting on every column except the first one

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
}
]

jquery datatable disable sort in specific row

How to disable sorting in specific row/column in jquery datatable using a class?
here's my sample table;
<table>
<thead>
<tr>
<th class="sorting_disabled">Title1</th>
<th class="">Title2</th>
<th class="sorting_disabled">Title3</th>
</tr>
</thead>
<tbody>
<tr><td>Tag 1</td><td>Date 1</td><td>Date 2</td></tr>
<tr><td>Tag 2</td><td>Date 2</td><td>Date 2</td></tr>
<tr><td>Tag 3</td><td>Date 3</td><td>Date 3</td></tr>
<tr><td>Tag 4</td><td>Date 4</td><td>Date 4</td></tr>
<tr><td>Tag 5</td><td>Date 5</td><td>Date 5</td></tr>
....
</tbody>
</table>
script;
$('.sortable thead tr th.sorting_disabled').livequery(function() {
$(this).removeClass('sorting');
$(this).unbind('click');
});
above code works but if I click to the next column who has a sorting its shows again an arrow. though its not clickable ;(
How can I disable the sorting by using a class and not using/redraw a table.
You can disable the sorting using a class in definition.
Just add this code to the datatable initialization:
// Disable sorting on the sorting_disabled class
"aoColumnDefs" : [ {
"bSortable" : false,
"aTargets" : [ "sorting_disabled" ]
} ]
$('#example').dataTable( {
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ 1 ] }
]});
That should do it..;)
The only solution:
First add class="sorting_disabled" to any<th> that you want to disable sorting, then add this code to the datatable initialization:
// Disable sorting on the sorting_disabled class
"aoColumnDefs" : [ {
"bSortable" : false,
"aTargets" : [ "sorting_disabled" ]
} ],
"order": [
[1, 'asc']
],
As said in the Datatables documentation:
As of DataTables 1.10.5 it is now possible to define initialisation options using HTML5 data-* attributes. The attribute names are read by DataTables and used, potentially in combination with, the standard Javascript initialisation options (with the data-* attributes taking priority).
Example:
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th data-orderable="false">Start date</th>
<th>Salary</th>
</tr>
</thead>
I strongly recommend using this approach, as it is more cleaner than others. DataTables 1.10.15 was originally released on 18th April, 2017.
try the following answer .it works for me.
<table class="tablesorter" id="tmp">
<thead>
<tr>
<th>Area</th>
<th>Total Visitors</th>
</tr>
</thead>
<tbody>
<tr>
<td>Javascript</td>
<td>15</td>
</tr>
<tr>
<td>PHP</td>
<td>3</td>
</tr>
<tr>
<td>HTML5</td>
<td>32</td>
</tr>
<tr>
<td>CSS</td>
<td>14</td>
</tr>
<tr>
<td>XML</td>
<td>54</td>
</tr>
</tbody>
<tfoot>
<tr class="no-sort">
<td><strong>Total</strong></td>
<td><strong>118</strong></td>
</tr>
</tfoot>
source : http://blog.adrianlawley.com/tablesorter-jquery-how-to-exclude-rows
<th class="sorting_disabled"> </th>
$(document).ready(function () {
$('#yourDataTableDivID').dataTable({
"aoColumnDefs": [
{
"bSortable": false,
"aTargets": ["sorting_disabled"]
}
]
});
});
I hope below code works in your case.
$("#dataTable").dataTable({
"aoColumns": [{"bSortable": false}, null,{"bSortable": false}]
});
You need to disable sorting via "bSortable" for that specific column.
$(document).ready(function() {
$('#example').dataTable( {
"aoColumns": [
{ "bSortable": false },
null,
{ "bSortable": false }
]
});
});
I came with almost the same solution like in the question, but I used the "fnHeaderCallback". As far as I understood, it gets called after each header redisplay, so no more worries about 'sorting' class that appears again after clicking on column next to target column.
$('.datatable').dataTable({
"fnHeaderCallback": function() {
return $('th.sorting.sorting_disabled').removeClass("sorting").unbind("click");
}
});
Additional documentation about callbacks: http://datatables.net/usage/callbacks
this code worked for me in react.
in row created i added fixed-row class to the row i wanted to stay fixed and not sortable and i drawcallback i hid the row then i appended it to the table itself.
Hope this works for you:
$(this.refs.main).DataTable({
dom: '<"data-table-wrapper"t>',
data: data,
language: {
"emptyTable": "Loading ...",
},
columns,
ordering: true,
order: [0,'asc'],
destory:true,
bFilter: true,
fixedHeader: {
header: true
},
iDisplayLength: 100,
scrollY: '79vh',
ScrollX: '100%',
scrollCollapse: true,
"drawCallback": function( settings ) {
var dataTableId = $("#To_Scroll_List").find(".dataTables_scrollBody table").attr("id");
$("..fixed-row").css('display','none');
$("#"+dataTableId+"_wrapper table").find('tbody tr:last').after($('.fixed-row'));
$(".fixed-row").show();
},
createdRow: function (row, data, index) {
if(data.UnitsPerLine == 999){
$(row).addClass('fixed-row');
}
},
initComplete: function (settings, json) {
$("#To_Scroll_List").find(".dataTables_scrollBodytable").attr("id");
$("#"+dataTableId+" thead tr").remove();
});
DatatableSearch(dataTableId+"_wrapper table", "AverageUnitsPerLineReport");
}
});
}
Without using class, you can follow these steps:
Remove the row which has to remain unsorted from the body of the table.
Include the row to be added in the footer of the table if it is the last row.
I did it including the code below in drawCallback:
drawCallback: function(settings) {
let td = $("td:contains('TOTAL')");
if (td.length) {
let row = td.closest('tr');
let clonedRow = row.clone();
row.remove();
$('table tbody').append(clonedRow);
}
}

Categories