Easy Code Share > HTML CSS > Advanced > jQuery Toggle Div and Table Row/Column in 5 Demos

jQuery Toggle Div and Table Row/Column in 5 Demos


To toggle table row/column for hiding or showing, we provide 5 jQuery illustrating examples, even including toggle div. This is a practical skill relating to jQuery and CSS. You will find a major concept about the skill throughout all 5 demos.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 9 minutes

 

 

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

 

Download Guideline

  • Prepare HTTP server such as XAMPP or WAMP in your windows environment.
  • Download and unzip into a folder that http server can access.
 DOWNLOAD SOURCE

 

DEMO 1
Toggle Table Row (i)

Let us start from the HTML attribute onclick in <td> elements. On clicking, it calls a function running jQuery codes to toggle table rows.

 

HTML Attribute – onclick

You can toggle a specific group or table rows. Now, let us category them to be All, Odd, and Even.

Toggle Table Row Using jQuery

For exmaple, provide that you click "Toggle Odd", the 3 white rows disappear. Of course, 3 rows will be back if clicking again.

Toggle Table Odd Row

Assume that real-world data should come from server sites, so we generate demo table data by embedded PHP codes, rather than by writing sample data into HTML elements in a manner not flexible.

In addition, from the codes below, you can see a toggle bar between table title and content rows. It has 3 buttons to manage actions to hide or show.

For example, HTML attribute type='odd' in toggle bar will influence all table rows with class='odd'. Therefore, to click it is to toggle odd-numbered rows.

toggle-1.php
<?php
$title = array("PRODUCT", "COLOR", "PRICE", "STOCK");
$products = array(
["iPad", "black", 400, 5], ["Camera", "gray", 180, 3],
["Bucket", "blue", 12, 7], ["Bottle", "pink", 15, 9],
["T-Shirt", "yellow", 20, 10], ["Coat", "navy", 35, 7]);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Demo 1: jQuery Toggle Table Row (onclick=...)</title>
    <meta charset="UTF-8">
    <meta name="description" content="Scripts for Learning Programming">
    <meta name="author" content="Easy Code Share">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <link rel="stylesheet" href="toggle.css">
</head>
<body>
    <table>
    <!-- Title -->
    <tr><?php foreach($title as $data) echo "<th>$data</th>"; ?></tr>
    <!-- Toggle Bar -->
    <tr class='bar'>
    <td onclick='toggle(this)' type='odd'>Toggle Odd</td>
    <td onclick='toggle(this)' type='even'>Toggle Even</td>
    <td onclick='toggle(this)' type='all'>Toggle All</td>
    <td></td></tr>
    <!-- Rows -->
    <?php foreach($products as $key=>$data) {
        $cls = (($key%2) == 0) ? $cls = "all odd" : $cls = "all even";
        echo "<tr class='$cls'>";
        foreach($data as $field) echo "<td>$field</td>";
        echo "</tr>";
    } ?>
    </table>
</body>
</html>
<script>
function toggle (e) {
    ele = "." + $(e).attr("type");
    if ($(ele).css("display") == "none")
        $(ele).show();
    else
        $(ele).hide();
}
</script>

Given HTML attribute onclick in <td> element like <td onclick='toggle(this)'>, when clicking, toggle() function runs to hide and show a selected group of rows.

Importantly in this example, because most run-time HTML codes was created by PHP scripts, you will not see that in toggle-1.php before running. To be familiar with run-time funtion F12 – Inspect in browsers, some notes on Learning Tips would be helpful.

 

DEMO 2
Toggle Table Row (ii)

Other than HTML attribute, we identify the <td> element by Id, and then keep listening clicks on it in jQuery.

 

Toggle Table by Element Id

Similar to Demo 1, this example also gets data from server sites. However, without onclick attribute, for each clicked <td> in <tr class='bar'>, jQuery retrieve Id like $(this).attr("id") to determine which table rows to toggle.

toggle-2.php
.....
<body>
    <table>
    <!-- Title -->
    <tr><?php foreach($title as $data) echo "<th>$data</th>"; ?></tr>
    <!-- Toggle Bar -->
    <tr class='bar'>
    <td id="odd">Toggle Odd</td>
    <td id="even">Toggle Even</td>
    <td id="all">Toggle All</td>
    <td></td></tr>
    <!-- Rows -->
    <?php foreach($products as $key=>$data) {
        $cls = (($key%2) == 0) ? $cls = "all odd" : $cls = "all even";
        echo "<tr class='$cls'>";
        foreach($data as $field) echo "<td>$field</td>";
        echo "</tr>";
    } ?>
    </table>
</body>
</html>
<script>
$(document).ready(function() {
    $('tr.bar td').on("click", function() {
        ele = "." + $(this).attr("id");
        if ($(ele).css("display") == "none")
            $(ele).show();
        else
            $(ele).hide();
    });
});
</script>

 

DEMO 3
Simple .toggle()

If no CSS helps, let us see how a single jQuery API toggle table rows.

 

jQuery API .toggle()

Briefly, this demo uses jQuery API .toggle() to replace .hide() and .show(). In short, when using .toggle() even without help of CSS, you can toggle table rows just like switching a device on or off.

We omit duplicated codes and only list codes about .toggle() as below.

toggle-3.php
.....
<script>
$(document).ready(function() {
    $('tr.bar td').on("click", function() {
        ele = "." + $(this).attr("id");
        /* duration:
           "fast" or 200 for FAST easing
           "slow" or 600 milliseconds for SLOW easing
        */
        duration = null;
        $(ele).toggle(duration);
    });
});
</script>

 

Duration for Easing Effect

With its rich variation, you can use .toggle() directly, or use .toggle(duration) with a duration time parameter to control disappearing speed. The larger the parameter is, the slower table rows are hiding or showing. As below, This is an intermediate view while setting easing duration as 600 milliseconds to toggle table rows.

Intermediate View When Using Easing Function

 

DEMO 4
Toggle Table Column

Apart from table rows, you may require the function of toggle table columns. We add additional checkboxes to present it to you.

 

Toggle Column

For vertically toggling, we let <input> element be a checkbox for each column. Once checked, the column is shown; otherwise, it vanishes. For example, Stock data don’t exist when unchecked.

Using CheckBox to Toggle Table Column

Stock Column Has Been Hidden

There must be a relationship to the upper checkbox and the content column. Surely, the attribute column='col-$col' in <input> element and the class='col-$col' in <th> and <td> element are what you have to link together.

Also, the F12 – Inspect in Learning Tips should be helpful, because that can show run-time HTML codes in browsers.

toggle-4.php
.....
<body>
    <!-- Column Toggle CheckBox -->
    <div class="check-area">
        <tr><?php foreach($title as $col=>$data) {
            echo "<input type='checkbox' column='col-$col' checked>";
            echo "<label style='font-weight:bold'>$data</label>&emsp;";
        }?></tr>
    </div>
    <table>
    <!-- Title -->
    <tr><?php foreach($title as $col=>$data) echo "<th class='col-$col'>$data</th>"; ?></tr>
    <!-- Rows -->
    <?php foreach($products as $key=>$data) {
        echo "<tr>";
        foreach($data as $col=>$field) {
            $cls = (($col%2) == 0) ? $cls = "odd" : $cls = "even";
            echo "<td class='$cls col-$col'>$field</td>";
        }
        echo "</tr>";
    } ?>
    </table>
</body>
</html>
<script>
$(document).ready(function() {
    $('div.check-area input').on("change", function() {
        ele = "." + $(this).attr("column");
        $(ele).toggle();
    });
});
</script>

 

DEMO 5
Toggle Div

DIV is a general element, so it can hold more kinds of materials like pictures than Table elements do. Here we introduce how to toggle div in a similar way.

 

Toggle Div

Alternatively, you can represent data using DIV elements. Each checkbox refers to a <div> such as <div class="name-iPad">. If checked, on checkbox, you can toggle Div containing the product of that name.

Show Data Rows Using Div

For example, if unchecking the checkbox for iPad, that <div> is hidden.

Hide iPad Row Using CheckBox

From view of programs, the entry='name-$data[0]' in <input> for checkbox is related to class='name-$data[0]' in <div>. Therefire, clicking on checkbox will result in the toggle of Div elements.

toggle-5.php
.....
<body>
    <!-- DIV Toggle CheckBox -->
    <div class="check-area">
        <tr><?php foreach($products as $key=>$data) {
            echo "<input type='checkbox' entry='name-$data[0]' checked>";
            echo "<label style='font-weight:bold'>$data[0]</label>&emsp;";
            //if($key==2) echo "<br>";
        }?></tr>
    </div>
    <!-- Title -->
    <div class="row" style="background:navy; color:white">
    <?php foreach($title as $data) echo str_replace(' ', '&nbsp;', sprintf("%20s", $data)); ?>
    </div>
    <!-- Rows -->
    <?php foreach($products as $key=>$data) {
        $cls = "row name-$data[0]";
        $cls = (($key%2) == 0) ? $cls .= " odd" : $cls .= " even";
        echo "<div class='$cls'>";
        foreach($data as $field) echo str_replace(' ', '&nbsp;', sprintf("%20s", $field));
        echo "</div>";
    } ?>
</body>
</html>
<script>
$(document).ready(function() {
    $('div.check-area input').on("change", function() {
        ele = "." + $(this).attr("entry");
        $(ele).toggle();
    });
});
</script>

At last, let us take a look at that all 5 demo examples use an identical CSS file as below.

toggle.css
body {background:#FAD0A0; font-family:Arial; font-size:1em}
table {width:600px; border-collapse:collapse; margin:5%;}
table, table tr, table tr th, table tr td {border:2px solid gray; padding:10px;}
table tr th {width:160px; background:navy; color:white;}
table tr td.all {width:160px; text-align:center;}
table tr.bar {background:#45B39D; color:white; cursor:pointer; text-align:center}
table tr.bar td:hover {background:#16A085;}
table tr.bar td {border-style:solid none solid none;}
div.check-area {width:540px; padding:2.5%; background:white; margin:5%}
div.row {width:580px; padding:10px; background:white; margin-left:5%}
.odd, div.odd {background:white;}
.even, div.even {background:lightgray;}
@media only screen and (max-width: 720px){
    table, div.check-area, div.row {margin:0%; width:100%}
    div.check-area {width:95%;}
}

 

FINAL
Conclusion

The 5 ways to toggle table row/column and div may help you realize the tricks of jQuery and CSS. Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!

 

Learning Tips

Let’s suggest a excellent way to learn HTML scripts here. Using Google Chrome F12 Inspect or Inspect Element will help you study the codes.

In Google Chrome, there are two ways to inspect a web page using the browser’s built-in Chrome DevTools:

  • Right-click an element on the page or in a blank area, then select Inspect.
  • Go to the Chrome menu, then select More Tools > Developer Tools.

 

Suggested Reading

 

TRY IT
Quick Experience

That’s all for this project, and here is the link that let you experience the program. Please kindly leave your comments for our enhancement.

 

Try It Yourself

Click here to execute the source code, thus before studying the downloaded codes, you can check whether it is worthy.

Leave a Comment