Hide column in a datatable with an if
datatables, jquery
Solution
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.
Problem
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;} ```