How to hide table columns in jQuery?

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?

Answers


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.


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.


Need Your Help

Not saving all data in cakephp

php cakephp

Im doing a simple save, and its not entering all the data. I have two models, message and emailmessage. The message table is getting populated ok, but the emailmessage table, is only getting the fo...

Re-arranging non-independent data from one df to another

r dplyr plyr data-manipulation

I am trying to rearrange some data from one dataframe to another. I think the solution I require will lie in the plyr package, but I have not been able to work out the full solution.