How to hide table columns in jQuery?

I have a table with a lot of columns. I want to give users the ability to select the columns that will be shown in the table. These options will be checkboxes along with column names. So how can I hide / show table columns based on checkboxes?

Will every td in every line be hidden (using .hide ())? Maybe I can assign a flag value to the location of the column in the table. Therefore, the first flag means the first column, and so on. And then recursively hide that 'numbered' td on each line. Will this work?

+6
jquery row show-hide
source share
2 answers

Try:

function hideColumn(columnIndex) { $('#mytable td:nth-child('+(columnIndex+1)+')').hide(); } 

This is a fairly simple version - it is assumed that your table does not use <TH> elements or has variable columns, but a basic concept exists. Note that nth-child uses 1-based indexing . I added 1 in the last step to make up for this.

+14
source share

I built a script that does what Rex offers. Each column has a flag (or element) that, when clicked, determines which column it is based on the nth descendant of, and then hides the same ones in every other TR.

Before .hide () I would add a class that could reference a column return.

The problem was that I was working with high-style tables in which some rows had colspans and some TDs had unique classes based on their position in the row. I talked about problems in IE where IE did not always show () hidden TDs with the correct style. It seemed that IE was unable to redraw the TDs.

+1
source share

All Articles