views:

176

answers:

2

I've a table with lots of columns. I want to give users the option to select columns to be shown in table. These options would be checkboxes along with the column names. So how can I hide/unhide table columns based on checkboxes?

Would hiding (using .hide()) each td in each row work? May be I can assign checkbox value to the location of column in table. So first checkbox means first column and so on. And then recursively hide that 'numbered' td in each row. Would that work?

+5  A: 

Try:

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

This is a pretty basic version - it assumes your table doesn't use <TH> elements or have variable column spans, but the basic concept is there. Note that nth-child uses 1-based indexing. I've added 1 at the latest stage to compensate for that.

Rex M
@understack: It would work with `<th>` if you change the function to `$('#mytable td:nth-child('+(columnIndex+1)+'), #mytable th:nth-child('+(columnIndex+1)+')').hide();`
fudgey
A: 

I built a script that does what Rex suggests. There's a check box (or element) in each column that, when clicked, figures out which column it's in based on the nth-child and then hides the same ones in each other TR.

Before .hide() I'd add a class that I could reference to return the column.

The issue I had is I was working with heavily styled tables where some rows had colspans and some TDs had unique classes based on their position in the row. I rant into issues in IE where IE wouldn't always show() the hidden TDs with the proper styling. It seemed that IE had trouble redrawing TDs.

DA