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

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/

Related

DataTable rows aren't turning into hrefs

I created a table with DataTables and at first the document titles that were rendered (from a local JSON file) were wrapped around anchor tags and turned into hrefs. I made some changes to my DataTable initialization and added some new columns to my table, and those things might have prevented the doc titles from turning into hrefs. I'm not 100% sure.
Importing table data:
loadTableData() {
$.noConflict();
let tableRes = KMdocs.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
"Path": obj.EncodedAbsUrl,
"Titles": obj.File.Name,
"Categories": obj.ResourceType.results.map(function(val) {
return val.Label;
}).join(";"),
"Blank": ""
}
});
}
Rendering table:
$('#km-table-id').DataTable({
columns: [
{ data: "Blank" },
{
data: "Titles",
columnDefs: [ // ----- I believe the issue is with this block
{
data: "Path",
ordering: true,
targets: [ 1 ],
render: function(data, type, row) {
return $('<a>')
.attr({target: "_blank", href: row.Path})
.text(data)
.wrap('<div></div>')
.parent()
.html();
},
targets: [1]
}
],
},
{
data: "Categories",
searchable: true,
targets: [ 2 ],
visible: false
},
{
data: "Blank"
}
],
data: tableRes,
language: { searchPlaceholder: "Search All Documents" },
lengthMenu: [ 10, 25, 50, 100, 250, 500 ],
order: [],
pageLength: 500,
paging: true,
pagingType: "full_numbers",
responsive: true,
scrollCollapse: true,
scrollXInner: true,
scrollY: 550,
sDom: '<"top">rt<"bottom"flp><"left">' // puts dropdown on bottom
});
HTML snippet:
<table id="km-table-id" class="cell-border display stripe-hover">
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Categories</th>
<th>My Favorites</th>
</tr>
</thead>
<tbody></tbody>
</table>

How to disable sorting on a column in a datatable

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

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

how to add data in datatable?

I am trying to add data dynamically in datatable.I have initialized table on document.ready and created an instance of it.After that, I am trying to add data in the table using instance.
$(document).ready(function() {
//Initialize tooltips
table_sgdFile_list_linked = $('#sgdFile_list_linked').DataTable({
bSort: false,
destroy:true,
bLengthChange: false,
pageLength: 4,
columns: [{
title: "Name"
},
{
title: "Action"
}
]
});
});
I am trying to bind the data
table_sgdFile_list_linked.data(dataSet)
but it is not working.
my_list = $('#my-table-html-id').DataTable( {
"processing": true,
"serverSide": false,
"paging": true,
"bLengthChange" : true,
"bFilter": false,
"pageLength": 10,
"info": false,
"ordering": true,
"ajax": "PATH-OF-MY-API",
"columnDefs": [
{
"render": function ( data, type, row ) {
var html = data + " Modified!";
return html;
},
"orderable": false,
"targets": 1 //Last column
},
],
})
you can try this:
to add 1 row: table_sgdFile_list_linked.row.add(rowJson).draw();
to add multiple rows: table_sgdFile_list_linked.rows.add(rowsJson).draw();
following worked for me :
table_sgdFile_list_linked.clear().draw();
$('#sgdFile_list_linked').dataTable().fnAddData(trHTML);

jQuery datatables TypeError: b is null

I am facing with a error fired by Firebug when using a jquery datatables plugin
The table is like this:
<table id="dt_cursuri" class="table table-striped table-bordered dTableR">
<thead>
<tr>
<th data-class="expand">Curs</th>
<th data-hide="phone,tablet" data-name="Assign">Domeniu</th>
<th>Tip</th>
<th>Data modif</th>
<th class="centered-cell">Actiuni</th>
</tr>
</thead>
<tbody>
<tr>
<td class="dataTables_empty" colspan="6">Fetching data from server</td>
</tr>
</tbody>
</table>
The datatables initialization:
var oTable;
var responsiveHelper = undefined;
var breakpointDefinition = {
tablet: 1024,
phone : 480
};
var oTable = $('#dt_cursuri');
oTable = $('#dt_cursuri').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sPaginationType": "bootstrap",
"sDom": "<'row'<'col-md-6'l><'col-md-6'f>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
"sAjaxSource": "view/cursuri/server_side.php",
autoWidth : false,
"fnPreDrawCallback": function () {
// Initialize the responsive datatables helper once.
if (!responsiveHelper) {
responsiveHelper = new ResponsiveDatatablesHelper(oTable, breakpointDefinition);
}
},
"fnDrawCallback" : function (oSettings) {
responsiveHelper.respond();
},
"fnRowCallback": function( nRow, aData ) {
responsiveHelper.createExpandIcon(nRow);
},
"aoColumns": [
//{ "sClass": "center", "bSortable": false, sWidth: '2%', "bVisible": false },
{ sWidth: '35%' },
{ sWidth: '25%' },
{ sWidth: '20%' },
{ sWidth: '10%' },
{ "sClass": "center", sWidth: '10%', "bSortable": false }
],
"aaSorting": [[2, 'asc']]
} );
The server side json file is working corectly. The same code is used in other tables that work perfect, but this one is not
Could someone help me?
The error is fired for this line from jquery.datatables.js:
!a.sLoadingRecords && (c && 'Loading...' === b.sLoadingRecords) && D(a, a, 'sZeroRecords', 'sLoadingRecords');
I will answer this question on my own thanks to developers of jQuery Datatables.
The problem was in the server side processing. When using diacritics the datatable is messing with the data so you have to actually control the diacritics with utf8_encode() php function

Categories

Resources