How to disable sorting on a column in a datatable - javascript

I'm trying to disable the sorting function on one of my columns.
I already have tried multiple things but these didn't work.
I tried adding this: data-sorter="false" to my <th> but it just ignored it.
I also have tried this but it also just ignored it:
“columnDefs”: [ {
“targets”: 2,
“orderable”: false
}]
When I tried these methods I did not get any errors.
I also found out using inspect element that my <th> automatically gets the class sorting added to it.
Here is my code:
My table:
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Vraag</th>
<th>Gepost op</th>
<th>Acties</th>// I want to disable sorting here
</tr>
</thead>
<tbody>
</tbody>
</table>
My js:
// Call the dataTables jQuery plugin
$(document).ready(function() {
$('#dataTable').DataTable({
"columnDefs": [ {
"targets": 2,
"orderable": false
} ]
});
});
Please help me I have been searching for an answer the last 3 days.

Did you try to set "bSort":false? For more details see THIS
Disable Sort from datatable
"bSort":false
To Disable sorting on particular column:
"bSortable": false
More specific:
$('#table').dataTable( {
"bSort":true,
aoColumnDefs: [
{ aTargets: [ '_all' ], bSortable: false },
{ aTargets: [ 0 ], bSortable: true },
{ aTargets: [ 1 ], bSortable: true }
]
}

Related

How to reload table data using DataTables, Ajax call & Json response?

I have a table that is generated through Thymeleaf. I would like to refresh the contents of the table using jQuery.
<table class="table table-hover" id="main-table">
<thead class="thead-inverse">
<tr>
<th class="col-md-2 text-center">Network Id</th>
<th class="col-md-2 text-center">Rep date</th>
<th class="col-md-2 text-center">Hashrate [KH/s]</th>
</tr>
</thead>
<tbody>
<tr th:each="networkHashrate : ${networkHashrates}" th:onclick="'javascript:openPoolModal(\''+ ${networkHashrate.id} + '\');'">
<td class="text-center" id="hashrateId" th:text="${networkHashrate.id}"> Sample id</td>
<td class="text-center" id="repDate" th:text="${#findAndDisplayDataService.formatDate(networkHashrate.repDate)}">Sample rep-date</td>
<td class="text-center" id="hashrate" th:text="${#findAndDisplayDataService.formatHashrate(networkHashrate.hashrate)}">Sample hashrate</td>
</tr>
</tbody>
</table>
I have come up with such function to update table contents every 8s:
$(document).ready(function() {
var table = $('#main-table').DataTable({
ajax: {
url: '/refresh',
dataSrc:''
},
paging: true,
lengthChange: false,
pageLength: 20,
stateSave: true,
info: true,
searching: false,
"aoColumns": [
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "desc", "asc" ] }
],
"order": [[ 0, "asc" ]]
});
setInterval(function(){
table.ajax.reload();
}, 8000);
});
Here's the JSON response:
[{
"id":1,
"repDate":{
"offset":{ },
"nano":880042000,
"year":2018,
"monthValue":4,
"dayOfMonth":25,
"hour":12,
"minute":58,
"second":53,
"month":"APRIL",
"dayOfWeek":"WEDNESDAY",
"dayOfYear":115
},
"hashrate":5114926.0
},...more entries
]
An empty table prints and I keep getting an error:
Uncaught TypeError: Cannot read property 'reload' of undefined
There's also an alert pop-up saying:
Data Tables warning: table id=main-table - Requestem unknown parameter '0' for row 0 column 0. For more information about this error, please see: http://datatables.net/tn/4
EDIT
I moved table declaration outside the function. Now I just keep getting the warning.
EDIT 2
I did as you stated, the data keeps refreshing, but there are still few issues.
First of all, my stateSave: true property stopped working, so when the table is reloaded it always gets back to the first page.
Secondly, I lost all my styling (class="text:center" for example) and on:click property that were originally in my html file.
Try to declare the table before the $(document).ready :
var table;
$(document).ready(function() {
table = $('#main-table').DataTable({"serverSide": true, ...})
setInterval(function(){
table.ajax.reload();
}, 8000);
})
The error is related to your column definition, try this way to define columns :
"columnDefs": [
{
"targets": 0,
"data": "id",
},
{
"targets": 1,
"data": "repDate",
},
{
"targets": 2,
"data": "repDate",
}
]

Reload dataTable from variable

I searched all over web and I didn't find easy solution for this. I'm using jQuery DataTables with "static" data source (one var is filled with data using SignalR and then later, DataTable is built). Now, when change of this dataset comes, I want to update table using this data set. Ideally, that would be simple "refresh" which reloads data from specified source. Here is my HTML
<table class="table table-hover table-condensed table-responsive" id="tableAccounts">
<thead>
<tr>
<th data-localize="_A_C">_A_C</th>
<th data-localize="_Name">_Name</th>
<th data-localize="_Address">_Address</th>
<th data-localize="_City">_City</th>
<th data-localize="_Phone">_Phone</th>
</tr>
</thead>
<tbody></tbody>
And here is my javascript which initially loads data:
tAccounts = $('#tableAccounts').dataTable({
"data": AccountAll,
"bFilter": true,
"pageLength": 100,
"bSearchable": true,
"bInfo": false,
"columns": [
{ "data": "AccountCode" },
{ "data": "Name" },
{ "data": "Address" },
{ "data": "City" },
{ "data": "Phone" }
],
"columnDefs": [
{
"render": function (data, type, row) {
return ("0000" + data.toString(16)).slice(-4);
},
"targets": 0
},
{ "visible": true, "targets": [0] }
]
});
tl;dr;
How to refresh datatable when data source (AccountAll in this case) is changed without destroying whole table? Bonus point if selection and filter is preserved.
Change can be anything. New row added, row removed, cell value changed.
You can use combination of clear() and rows.add() API methods to clear existing data and add updated data.
In this case filtering and sorting would be preserved.
If you want to preserver the current page, call draw(false) instead of draw() but if you're adding new rows, there is little sense in preserving the current page
For example:
var data = [['old',2,3,4,5,6]];
var table = $('#example').DataTable({
'data': data
});
var dataNew = [['new',2,3,4,5,6]];
table.clear().rows.add(dataNew).draw();
See this example fro code and demonstration.

How to hide the columns in Table using Jquery Data Table Plugin?

I'm using the jQuery Data Table Plugin.
I tried to use columnDef to hide some of the columns, but they still appear.
How can I use columnDef to hide some of the columns?
Here is my code:
<div id="LabResultDataTableView">
<table id="TimelineTableTester" class="table table-striped table-bordered">
<thead class="td-datatable">
#foreach (var data in Model.ColumnNames)
{
<th style="background-color: inherit !important;">#data</th>}
}
</thead>
<tbody>
#for (int i = 0; i < Model.columnValuesRowWise.Count; i++)
{
<tr>
#foreach (var col in Model.columnValuesRowWise[i])
{
<td>#col</td>
}
</tr>
}
</tbody>
</table>
</div>
$(document).ready(function () {
debugger;
ProceduresAndOfficeVisitsDataView = $('#TimelineTableTester').DataTable({
"bProcessing": true,
"bDeferRender": true,
"scrollX": true,
"bSort": false,
"stateSave": true,
"bAutoWidth": true,
"columnDefs": [
{
"targets": [0],
"visible": false,
},
{
"targets": [11],
"visible": false,
},
{
"targets": [12],
"visible": false,
}]
});
});
Well first thing you have the syntax error in your code, there is an extra , after "visible": false.
Second you don't need to specify the column hiding logic for every column separately, you can specify it like
"columnDefs": [
{
"targets": [0, 11, 12],
"visible": false
}
]
Third thing "visible": false does the trick for column hiding but by any chance if its not happening you can add your custom class for hiding the column like below
"columnDefs": [
{
"targets": [0, 11, 12],
"sClass": "dt_col_hide"
}
]
with class definition as
.dt_col_hide{
display: none;
}
Demo : https://jsfiddle.net/Prakash_Thete/qef33kox/

jquery datatables: adding extra column

Scenario
I am using datatables (#version 1.9.4) for the first time to display data to the user.
I succeed in retrieving the data via ajax and in binding them to the datatable.
Now I want to add extra columns to let the user process the records. For semplicity sake, the aim is to add a button with an onclick handler that retrieve the data of the 'clicked' record.
In my plan I would bind the json item corresponding to the 'clicked' record to the onclick handler.
Till now, if I add an additional TH for the action column to the DOM, an error occurs from datatables code:
Requested unknown parameter '5' from data source for row 0
Question
How to set custom columns? How to fill their content with HTML?
Here is my actual config.
HTML
<table id="tableCities">
<thead>
<tr>
<th>country</th>
<th>zip</th>
<th>city</th>
<th>district code</th>
<th>district description</th>
<th>actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
Javascript
$('#tableCities').dataTable({
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": true,
"bInfo": false,
"bAutoWidth": true
, "bJQueryUI": true
, "bProcessing": true
, "bServerSide": true
, "sAjaxSource": "../biz/GetCitiesByZip.asp?t=" + t
});
Sample Json result
{
"aaData":
[
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino"
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino"
]
],
"iTotalRecords": 2,
"iTotalDisplayRecords": 2,
"iDisplayStart": 0,
"iDisplayLength": 2
}
Edit
Daniel is right. The solution is to set up the custom column in the aoColumnDefs, specifying the mData and the mRender properties. In particular mRender lets to define custom html and javascript.
/* inside datatable initialization */
, "aoColumnDefs": [
{
"aTargets": [5],
"mData": null,
"mRender": function (data, type, full) {
return 'Process';
}
}
]
You can define your columns in a different way
like this
"aoColumns": [
null,
null,
null,
null,
null,
{ "mData": null }
]
or this
"aoColumnDefs":[
{
"aTargets":[5],
"mData": null
}
]
Here some docs Columns
Take a look at this DataTables AJAX source example - null data source for a column
Note that prior to DataTables 1.9.2 mData was called mDataProp. The name change reflects the flexibility of this property and is consistent with the naming of mRender. If 'mDataProp' is given, then it will still be used by DataTables, as it automatically maps the old name to the new if required.
Another solution/workaround could be adding that '5' parameter...
For example adding extra "" to each row
like this:
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino",
""
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino",
""
]
Just in case anyone using a newer version of DataTables (1.10+) is looking for an answer to this question, I followed the directions on this page:
https://datatables.net/examples/ajax/null_data_source.html
Posting this answer here, just to show that where the aoColumnDefs needs to be defined. I got help from this question it self, but I struggled for a while for where to put the aoColumnDefs. Further more also added the functionality for onclick event.
$(document).ready(function() {
var table = $('#userTable').DataTable( {
"sAjaxSource": "/MyApp/proctoring/user/getAll",
"sAjaxDataProp": "users",
"columns": [
{ "data": "username" },
{ "data": "name" },
{ "data": "surname" },
{ "data": "status" },
{ "data": "emailAddress" },
{ "data" : "userId" }
],
"aoColumnDefs": [
{
"aTargets": [5],
"mData": "userId",
"mRender": function (data, type, full) {
return '<button href="#"' + 'id="'+ data + '">Edit</button>';
}
}
]
} );
$('#userTable tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
console.log(data);
$('#userEditModal').modal('show');
});
} );

Datatables with rowGrouping unable to hide columns

The JS:
$(document).ready(function() {
// $( "#dashboard_container" ).tabs();
$('#listings').dataTable({
"bRetrieve": true,
"aoColumns":
[
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
{ "bVisible": false },
]
}).rowGrouping({
iGroupingColumnIndex: 1,
sGroupingColumnSortDirection: "asc",
iGroupingOrderByColumnIndex: 0,
bExpandableGrouping: true,
bExpandSingleGroup: true,
iExpandGroupOffset: -1
});
});
The HTML:
<table class="datatable" id="listings">
<thead>
<tr>
<th>Group Index</th><th>Group Display Name</th>
<th>Organization</th>
<th>Volumes</th>
<th>Read (MB/s)</th>
<th>Write (MB/s)</th>
<th>Volume Size (GB)</th>
<th>My Cost (USD)</th>
<th>Comments</th>
</tr>
</thead>
<tfoot></tfoot>
<tbody>
<tr>
<td>0</td><td>Artful Scientific</td>
<td>Something Co.</td>
<td>information</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>$0</td>
<td><a class="btn small icon i_preview comment_edit_button" rel="1" title="edit or view comment">View</a></td>
</tr>
</tbody>
</table>
</div>
The problem:
I am able to successfully do the row groupings and it works fine, however I have a need where I need to hide 2 of the columns to certain roles. As well as hide an additional column which would be the Equivlent of the "Organization" column which the grouping uses. However from the above JS you can see I have tried hiding all columns just to see if any would actually hide in my last ditch effort before coming here. No matter which ones all or one none will hide. Anyone know a work around for this? As I need the columns to remain but hidden to the actual view
hide column using this command and first parameter is index of the column and
second parameter is visibilty
fnSetColumnVis( 1, false );

Categories

Resources