This tutorial will demonstrate how to hide or expose a column in a jQuery datatable based on a condition. This will teach us how to dynamically display and conceal a datatable column. A datatable’s columns can be dynamically shown and hidden by using the column().visible() API method.
table().Based on a criterion, the visible() function is used to reveal and hide columns in a datatable. Moreover, the visibility of a single or multiple selected columns can be obtained or changed.
Let’s see, then. Datatable columns can be hidden using jQuery, shown and hidden dynamically in datatables, dynamically added columns can be shown and hidden in datatables using jQuery, and dynamically hidden and shown columns can be dynamically added to datatables using Laravel 9.
Example:
var table = $('#example').DataTable();
alert( 'Column index 1 is '+
(table.column( 1 ).visible() === true ? 'visible' : 'not visible')
);
Html:
<div>
Toggle column: <a class="toggle-vis" data-column="0">Name</a> - <a class="toggle-vis" data-column="1">Position</a> - <a class="toggle-vis" data-column="2">Office</a> - <a class="toggle-vis" data-column="3">Age</a> - <a class="toggle-vis" data-column="4">Start date</a> - <a class="toggle-vis" data-column="5">Salary</a>
</div>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Angelica Ramos</td>
<td>Chief Executive Officer (CEO)</td>
<td>London</td>
<td>47</td>
<td>2009-10-09</td>
<td>$1,200,000</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
JQuery:
$(document).ready(function () {
var table = $('#example').DataTable({
scrollY: '200px',
paging: false,
});
$('a.toggle-vis').on('click', function (e) {
e.preventDefault();
// Get the column API object
var column = table.column($(this).attr('data-column'));
// Toggle the visibility
column.visible(!column.visible());
});
});
I’m Abhishek, a DevOps, SRE, DevSecOps, and Cloud expert with a passion for sharing knowledge and real-world experiences. I’ve had the opportunity to work with Cotocus and continue to contribute to multiple platforms where I share insights across different domains:
-
DevOps School – Tech blogs and tutorials
-
Holiday Landmark – Travel stories and guides
-
Stocks Mantra – Stock market strategies and tips
-
My Medic Plus – Health and fitness guidance
-
TrueReviewNow – Honest product reviews
-
Wizbrand – SEO and digital tools for businesses
I’m also exploring the fascinating world of Quantum Computing.
[…] Hide/Show Column in jQuery Datatable Dependent on Condition […]
[…] Hide/Show Column in jQuery Datatable Dependent on Condition […]