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" >
<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 >
<button type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span >Columns</span>
</button>
<div >
<a href="#" 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.
CodePudding user response:
In the end, your approach is correct - with one small change: Move the following line (which toggles the column's visibility)...
column.visible(!column.visible());
...from inside the if
statement to before the if
statement.
That will ensure the toggle always happens for the selected column.