How to Hide and Show the Table column using jQuery

In this tutorial, we will learn How you can use jQuery to show and hide the table column.

When does it require ?

When the table has multiple columns and you want to allow the user to hide and show those columns which user doesn’t want to see on the screen. This gives more flexibility to the user.

What in the Demonstration ?

In the demonstration, we will create a Table structure which shows employees list and adding some checkboxes. When checkboxes get checked then hiding the Table column based on selection and reset it when it is unchecked.

How to Hide and Show the Table column using jQuery


Contents

  1. Table structure
  2. Configuration
  3. HTML and PHP
  4. jQuery
  5. Conclusion

 


1. Table structure

We are only using one Table in the tutorial example. employee table.

CREATE TABLE `employee` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `emp_name` varchar(100) NOT NULL,
  'salary' varchar(20) NOT NULL,
  'gender' varchar(10) NOT NULL,
  'city' varchar(80) NOT NULL,
  'email' varchar(100) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

2. Configuration

Create a new PHP file (config.php). This file contains database connection. In this tutorial, we are using a tutorial database.

Completed Code

<?php

$host = "localhost";    /* Host name */
$user = "root";         /* User */
$password = "";         /* Password */
$dbname = "tutorial";   /* Database name */

$con = mysql_connect($host, $user, $password) or die("Unable to connect");

// selecting database
$db = mysql_select_db($dbname, $con) or die("Database not found");

 

3. HTML and PHP

Using PHP only to show records in the table element.

Creating a Table element with id=”emp_table” which have 6 columns for S.no, Name, Salary, Gender, City, and Email. And also creating checkboxes above of Table element, which we use to show or hide the column. This we do use jQuery.

In jQuery, for performing an operation on Table column require column number. For this add id to checkboxes which contains column number separated with and underscore (_) e.g. col_1, col_2, col_3, etc.

And also added hidecol class to it for detecting click event in jQuery.

Completed Code

<?php
    include("config.php");
?>
<!doctype html>
<html>
<head>
    <title>How to Hide and Show the Table column using jQuery</title>
    <link href="style.css" type="text/css" rel="stylesheet">
    <script src="jquery-1.12.0.min.js" type="text/javascript"></script>
    <script src="script.js" type="text/javascript"></script>

</head>
<body>
<div class="container">
    <div>
        <strong>Checked the Checkbox for Hide column</strong>
        <input type="checkbox" class="hidecol" value="name" id="col_2" />&nbsp;Name&nbsp;
        <input type="checkbox" class="hidecol" value="salary" id="col_3" />&nbsp;Salary
        <input type="checkbox" class="hidecol" value="gender" id="col_4" />&nbsp;Gender
        <input type="checkbox" class="hidecol" value="city" id="col_5" />&nbsp;City
        <input type="checkbox" class="hidecol" value="email" id="col_6" />&nbsp;Email
    </div>
    <table width="100%" id="emp_table" border="0">
        <tr class="tr_header">
            <th>S.no</th>
            <th>Name</th>
            <th>Salary</th>
            <th>Gender</th>
            <th>City</th>
            <th>Email</th>
        </tr>
        <?php

        // selecting rows
        $sql = "SELECT * FROM employee ORDER BY ID ASC";
        $result = mysql_query($sql);
        $sno = 1;

        while($fetch = mysql_fetch_array($result)){
            $name = $fetch['emp_name'];
            $salary = $fetch['salary'];
            $gender = $fetch['gender'];
            $city = $fetch['city'];
            $email = $fetch['email'];
            ?>
            <tr>
                <td align='center'><?php echo $sno; ?></td>
                <td align='center'><?php echo $name; ?></td>
                <td align='center'><?php echo $salary; ?></td>
                <td align='center'><?php echo $gender; ?></td>
                <td align='center'><?php echo $city; ?></td>
                <td align='center'><?php echo $email; ?></td>
            </tr>
            <?php
            $sno ++;
        }
        ?>
    </table>

</div>
</body>
</html>

 

4. jQuery

Create a new script file name it script.js. From there, we perform column hiding operation.

Explanation

Using hidecol class to detect click event on Checkboxes instead of using id.

Splitting the id for getting the column number using the split() function and storing column number to colno variable and created a Boolean variable which is initialized to true when Checkbox checked otherwise false.

For checking Checkbox checked or not we are using is() function.

Displaying show or hide the column with little delay, defined setTimeOut() function for it. If the Boolean variable is true it means checkbox state is the checked, in this case, we hide the column.

Selecting the all <td> cells of column by nth-child in which column number is passed same for <th> tag.

Note- If you are using <td> tag for creating table header you don’t need to execute following code

$('#emp_table th:nth-child('+colno+')').hide();

and

$('#emp_table th:nth-child('+colno+')').show();

Completed Code

$(document).ready(function(){

    // Checkbox click
    $(".hidecol").click(function(){

        var id = this.id;
        var splitid = id.split("_");
        var colno = splitid[1];
        var checked = true;
         
        // Checking Checkbox state
        if($(this).is(":checked")){
            checked = true;
        }else{
            checked = false;
        }
        setTimeout(function(){
            if(checked){
                $('#emp_table td:nth-child('+colno+')').hide();
                $('#emp_table th:nth-child('+colno+')').hide();
            } else{
                $('#emp_table td:nth-child('+colno+')').show();
                $('#emp_table th:nth-child('+colno+')').show();
            }

            // Hiding column

        }, 1500);

    });
});


 

5. Conclusion

We learned that How you can use jQuery to Show/Hide the Table columns. For this, we used checkboxes in the tutorial demonstration you can use any other elements e.g dropdown, radio button, etc.

Hiding the Table column when Checkbox gets checked otherwise resetting the column. For show/hide the column we have used nth-child() function in which we passed column position.

Related Post

Spread the love

One Comment

  1. Abbas said:

    Thanks Y sir Its very helpful me. Great job sir.

    March 6, 2017
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *