I have an HTML table with several columns and I need to implement a column chooser using jquery. When a user clicks on a checkbox I want to hide/show the corresponding column in the table. I would like to do this without attaching a class to every td in the table, is there a way to select an entire column using jquery? Below is an example of the HTML.
<table>
<thead>
<tr><th class="col1">Header 1</th><th class="col2">Header 2</th><th class="col3">Header 3</th></tr>
</thead>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
</table>
<form>
<input type="checkbox" name="col1" checked="checked" /> Hide/Show Column 1 <br />
<input type="checkbox" name="col2" checked="checked" /> Hide/Show Column 2 <br />
<input type="checkbox" name="col3" checked="checked" /> Hide/Show Column 3 <br />
</form>
One line of code using jQuery which hides the 2nd column:
If your table has header(th), use this:
Source: Hide a Table Column with a Single line of jQuery code
jsFiddle to test the code: http://jsfiddle.net/mgMem/1/
If you want to see a good use case, take a look at my blog post:
Hide a table column and colorize rows based on value with jQuery.
The following should do it:
This is untested code, but the principle is that you choose the table cell in each row that corresponds to the chosen index extracted from the checkbox name. You could of course limit the selectors with a class or an ID.
Personally, I would go with the the class-on-each-td/th/col approach. Then you can switch columns on and off using a single write to className on the container, assuming style rules like:
This is going to be faster than any JS loop approach; for really long tables it can make a significant difference to responsiveness.
If you can get away with not supporting IE6, you could use adjacency selectors to avoid having to add the class attributes to tds. Or alternatively, if your concern is making the markup cleaner, you could add them from JavaScript automatically in an initialisation step.
you could use colgroups:
your script then could change just the desire
<col>
class.And of course, the CSS only way for browsers that support
nth-child
:table td:nth-child(2) { display: none; }
This is for IE9 and newer.
For your usecase, you'd need several classes to hide the columns:
ect...