Using jQuery to Show and Hide Columns in a Table using CheckBoxes

Posted by: Suprotim Agarwal , on 4/25/2015, in Category jQuery and ASP.NET
Views: 119635
Abstract: Use jQuery to show hide columns depending on the checkbox you selected. We will also see how to show hide columns using header index.

This article talks about a common requirement in enterprise dashboards where you have a bunch of columns in a table and you want to show hide columns, depending on the checkbox you selected.

The approach is to create a bunch of checkboxes that match the number of columns in the table, as well as assign the same class as that of the checkboxes to the header as well as cells of each column in the table.

Create a new file called ‘HideShowColumns.html’.

Here’s a subset of the markup we are using. The complete markup can be viewed in the source code accompanying this article:

<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>

If you observe, the first cell of each column has a class ‘empid’ which matches the class of checkbox ‘EmployeeID’. To show/hide the column when a corresponding checkbox is clicked, use this code:

$(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();
    });
});

Start by caching the selector that selects all checkboxes inside the div grpChkBox. Similarly you can even cache $(“#someTable”) for a tiny performance benefit.

Then check all checkboxes at page load. Since it’s a bunch of checkboxes that you have to mark as checked together, use prop() that can set one or more properties (in our case checked) for every matched elements.

From jQuery 1.6 onwards, you should use prop() and not attr()

In the click event of any of the checkboxes, use $(this).attr("name") to determine the class name of the checkbox that was clicked. Then construct a selector of all cells matching this class using $tbl.find() to find all cells with the class name. This will give you some performance improvement especially if you are using the code on a page that has a couple of tables. This line prevents the code to search through every DOM element to find the table and class names; rather it only looks for children rows under the table someTable.

In the beginning, I told you that we are assigning the same class to the cells of each column as that of the checkboxes. Now all we need to do is show/hide it using toggle().

This is done using this simple line of code which toggles the visibility of the columns:

$(colToHide).toggle();

Live Demo: http://www.jquerycookbook.com/demos/S3-TablesTabsPanels/21-HideShowColumns.html

Show and Hide Columns in a Table using CheckBoxes Based on Header Index

So far, we looked at an ideal scenario where the cells and header of the table were marked with the same class name corresponding to the checkboxes. But what if there are no classes marked on the individual cells and basically you are feeling lazy to go ahead and add classes on all the rows. In this case, just mark the header row with classes corresponding to the ones on the checkboxes and use the solution demonstrated in this recipe.

Create a new file called ‘HideShowColumnsOnIndex.html’.

Observe this markup subset where the classes have been removed from all rows in the table body. The complete markup can be viewed in the source code accompanying this article.

<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>

In order to show/hide columns when the checkbox is clicked, use this code:

$(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();
    });
});

As you can observe, we have changed a couple of things as compared to our previous example. The first change is I have cached two selectors, the first that references the table and the other that references only the header of the table.

var $tbl = $("#someTable");
var $tblhead = $("#someTable th");

Next observe the code inside the checkbox click event.

var colToHide = $tblhead.filter("." + $(this).attr("name"));
var index = $(colToHide).index();
$tbl.find('tr :nth-child(' + (index + 1) + ')').toggle();

Since $tblhead contains only the header’s (th) of the table, instead of looking for children using find(), this time we use filter() to match the header with the corresponding checkbox class.

Once we have the table header we need, we retrieve the index of the column header. For this we use index(). As the jQuery documentation states "If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements". In our case, index function returns index based on the filter we provide, starting with 0 for first table header, 1 for second table header and so on.

The nth-child selector is fantastic. All you need to give it, is an integer like nth-child(1) and it will select all rows index.

:nth-child() is the only jQuery selector that is one-based. The jQuery documentation says "jQuery's implementation of :nth- selectors is strictly derived from the CSS specification, the value of n is "1-indexed", meaning that the counting starts at 1". Since the index() method in the previous line starts with zero, hence we are saying (index + 1) to reference the first column in the table.jquery-showhide-columns

Live Demo: http://www.jquerycookbook.com/demos/S3-TablesTabsPanels/22-HideShowColumnsOnIndex.html

Download the entire source code of this article (Github)

If you liked this article, take a look at my new book The Absolutely Awesome jQuery Cookbook which contains scores of practical jQuery/jQueryUI recipes you can use in your projects right away.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Michael on Thursday, April 30, 2015 9:39 PM
Can you please demo this using a gridview? Using jQuery to Show and Hide Columns in a Table using CheckBoxes
I need help. I have a grid view In one colnmn I display users productivity in minutes in another column I show the same in seconds. I would like to have one displayed at a time where the user can toggle between the two. Thanks in advance.
Comment posted by Asad Raza on Monday, May 4, 2015 1:36 AM
Great Article.