I am trying to show/hide datatable columns dynamically. For this, here I am going with the example which is given by the official datatable website.
This is the code for my datatable:
HTML:
<table id="itemEdit" class="table collapsed">
<thead>
<tr>
<th>ID</th>
<th>SKU</th>
<th>Barcode</th>
<th>Item Name</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
JS:
var tableId = "#itemEdit";
var $_table = $(tableId).DataTable({
//dom: "Bfrtip",
scrollY: "300px",
scrollX: true,
scrollCollapse: true,
"ajax": './view_items.php',
"columns": [
{"data": "id", "class": "align-middle"},
{"data": "sku","class": "align-middle"},
{"data": "barcode","class": "align-middle"},
{"data": "itemname","class": "align-middle"},
{"data": "price","class": "align-middle"},
]
})
HTML for <a>:
<div class="btn-group dropright dd-backdrop">
<button type="button" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Columns</span>
</button>
<div class="dropdown-menu p-0 ">
<a href="#" class="dropdown-item toggle-vis" data-column="4">
Item Name
</a>
</div>
</div>
My question is, just I want to add CSS class for the a.toggle-vis base on its visibility.
I tried it something like this. But its not working for me.
$('a.toggle-vis').on('click', function (e) {
e.preventDefault();
// Get the column API object
var column = $_table.column($(this).attr('data-column'));
//console.log(column)
if (column.visible() === true) {
$(this).addClass('showing').removeClass('not-showing');
column.visible(!column.visible());
} else {
$(this).removeClass('showing').addClass('not-showing');
$(this).removeClass('active');
}
$_table.columns.adjust().draw( false ); // adjust column sizing and redraw
});
Hope somebody may help me out.
$_table.column()ortable.column()?if (column.visible() === true), you can just useif (column.visible())- that will evaluate totrueorfalse. And (b) Did you pre-populate your<a>elements with the initial extra classshowing? Finally (c) I am not sure what$(this).removeClass('active');achieves since that class does not exist in the page (at least not in the demo you linked to ).if (column.visible())then its working at first, but then its not working and I can't get the column visible. (b) I need thosecssclasses to style<a>based on its visibility. (c) actually its not needed