I was looking trough the web on how to use javascript to hide columns and filter a table trough columns none of the datatables or other libraries provided me this solution. Until I hit the https://www.dotnetcurry.com/jquery/1122/jquery-show-hide-table-column-using-checkbox (searching on Google on hide columns that contain Jquery).
As they explain in the article you have two alternatives the hard one and the lazy one.
The hard one is basicly guiving each first element or second depending one the index the same class name and using javascript hide all of them on clicking on the corresponding checkbox.
<div id="grpChkBox"> <p><input type="checkbox" name="empid" /> Employee ID</p> <p><input type="checkbox" name="fname" /> First Name</p> ... <table id="someTable"> <thead> <tr> <th class="empid">EmpId</th> <th class="fname">First Name</th> ... </tr> </thead> <tbody> <tr> <td class="empid">E342</td> <td class="fname">Bill</td> ... </tr> <tr> <td class="empid">E343</td> <td class="fname">Laura</td> ... </tr> </tbody> </table>
$(function () { var $chk = $("#grpChkBox input:checkbox"); // cache the selector var $tbl = $("#someTable"); $chk.prop('checked', true); // check all checkboxes when page loads $chk.click(function () { var colToHide = $tbl.find("." + $(this).attr("name")); $(colToHide).toggle(); }); });
The second won for lazy people like me is to use their amazing recipe where you only put a unique class to each header.
<div id="grpChkBox"> <p><input type="checkbox" name="empid" /> Employee ID</p> <p><input type="checkbox" name="fname" /> First Name</p> ... <table id="someTable"> <thead> <tr> <th class="empid">EmpId</th> <th class="fname">First Name</th> ... </tr> </thead> <tbody> <tr> <td>E342</td> <td>Bill</td> ... </tr> </tbody> </table>
$(function () { var $chk = $("#grpChkBox input:checkbox"); var $tbl = $("#someTable"); var $tblhead = $("#someTable th"); $chk.prop('checked', true); $chk.click(function () { var colToHide = $tblhead.filter("." + $(this).attr("name")); var index = $(colToHide).index(); $tbl.find('tr :nth-child(' + (index + 1) + ')').toggle(); }); });
And let’s say you have a long list of headers and you don’t want to enter them manually. Let’s loop trough the list and and insert smartly the different filters class my using classLirst.add() functionality.
var S = "fullweb"; S.includes(test); function myFunction() { var element = document.getElementById("myDIV"); element.classList.add("mystyle"); }
2 replies on “Hide columns and filter table by columns”
Bookmarked!, I really like your website!
Thank you 🙂 !