6

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

1

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

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

UPDATE

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

6 Comments

Great example! -- Had a few HTML errors, however. jsfiddle.net/highwayoflife/8BahZ/1
works great. what if I wanted to have a box that is unchecked by default, but it needs to hide the corresponding column until it has be checked by the user.
It did not. I removed "checked" from one of the checkboxes and it did not work here jsfiddle.net/8BahZ
@highway of life, thanks for pointing that out. @Brad hhmm weird, it did for me, once one is checked the corresponding column has to disappear right? check here one last time: jsfiddle.net/8BahZ/3
I want 2 out of the 3 checked by default. If the checkbox is checked, display the column, if it is not checked, do not display the column. Sorry if I confused you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.