'Hide column in a datatable with an if
I'm new to jquery and datatable but learning quickly.
I want to hide specifics columns according to the value of a variable that I'll test with an if. But I don't know where to put said if and the code to hide the columns.
HTML:
<table id="table_id" class="table table-striped table-bordered table hover" width="100%" cellspacing="0" >
<thead>
<tr>
<th>Have</th>
<th>A</th>
<th>Good</th>
<th>Day</th>
</tr>
</thead>
Jquery:
$(document).ready( function () {
$('#table_id').DataTable({
"processing": true,
"order": [[ 3, "desc" ]],
"ajax": {
"url": "somewhere.php",
"type": "POST"
},
"columns": [
{ "data": "Have" },
{ "data": "A" },
{ "data": "Good" },
{ "data": "Day" }
]
});
} );
Pseudo code for the if
if($_POST('something') =="hey"){
hide column 1 and 2;}
Solution 1:[1]
HTML-sourced or JavaScript-sourced data
Use initComplete option to define a callback fired once table has been initialized. Use columns().visible() API method to hide selected columns based on your condition.
For example:
var table = $('#example').DataTable({
initComplete: function(settings){
var api = new $.fn.dataTable.Api( settings );
// Replace with your actual condition
var showColumn = Math.round(Math.random()) ? true : false;
api.columns([4, 5]).visible(showColumn);
}
});
See this example for code and demonstration.
Ajax-sourced data
Handle xhr event fired when an Ajax request is completed. Use columns().visible() API method to hide selected columns based on your condition.
For example:
$('#example').on('xhr.dt', function ( e, settings, json, xhr ) {
var api = new $.fn.dataTable.Api( settings );
// Replace with your actual condition
var showColumn = Math.round(Math.random()) ? true : false;
api.columns([4, 5]).visible(showColumn);
});
var table = $('#example').DataTable({
ajax: 'https://gyrocode.github.io/files/jquery-datatables/arrays.json'
});
In the above example, json variable holds response from the server which you can use to define your condition for showing/hiding columns.
Also please note that xhr event handler has to be defined BEFORE you call DataTable().
See this example for code and demonstration.
Solution 2:[2]
In ajax:
First get the table:
let datatable = $('#table-recaptures').DataTable();
Then get the column: //The zero in this case
let column_zero = datatable.column( 0 );
Later, for ocult
`column.visible( false )`;
For visible
column.visible( true);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Agustín Tamayo Quiñones |
