Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hide table columns automatically by checking a checkbox with jQuery

Tags:

html

jquery

I want to display 3 checkboxes that are pre-checked, but as soon as the user unchecks a box, the related column disappears.

<p><input type="checkbox" name="first_name" checked> First Name</p>
<p><input type="checkbox" name="last_name" checked> Last Name</p>
<p><input type="checkbox" name="email" checked> Email</p>

Rendered html of the table

<table id="report>
<thead>
<tr>
 <th class="first_name">First Name</th>
 <th class="last_name">Last Name</th>
 <th class="email">Email</th>
</tr>
</thead>
<tbody>
<tr>
 <td class="first_name">Larry</td>
 <td class="last_name">Hughes</td>
 <td class="email">[email protected]</td>
</tr>
<tr>
 <td class="first_name">Mike</td>
 <td class="last_name">Tyson</td>
 <td class="email">[email protected]</td>
</tr>
</tbody>
</table>

I imagine it will have to do with a live click event, setting the each class to .hide()

Any help is appreciated

like image 532
Brad Avatar asked Jan 12 '11 19:01

Brad


2 Answers

To have columns hidden automatically for checkboxes that are hidden by default (page load), use the following code along with the click element to toggle the columns:

$("input:checkbox:not(:checked)").each(function() {
    var column = "table ." + $(this).attr("name");
    $(column).hide();
});

$("input:checkbox").click(function(){
    var column = "table ." + $(this).attr("name");
    $(column).toggle();
});

Demo: http://jsfiddle.net/highwayoflife/8BahZ/4/

This example also uses a selector like: $('table .class_name'); which will be a faster selector if you are using the code on a larger page since it won't have to search through every DOM element to find the class names, it only looks under tables.

like image 62
Highway of Life Avatar answered Nov 20 '22 20:11

Highway of Life


$("input:checkbox").click(function(){
      var column = "."+$(this).attr("name");
      $(column).toggle();
});

UPDATE

Check out the online demo here: http://jsfiddle.net/8BahZ/

like image 41
amosrivera Avatar answered Nov 20 '22 21:11

amosrivera