Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 281
understack Avatar asked Apr 07 '10 20:04

understack


People also ask

How to hide table in jQuery?

The table is referred by a class selector in the hide jQuery method with fast duration. }); In the click event of button, tr:odd selector is used with table class to hide the rows. You may simply use “tr:odd” as well, however, this will hide all tables odd rows in the web page.

How do you hide and show table columns in HTML?

To hide a column entirely from view, meaning it will not be displayed in either the normal or details row, simply use the visible column option and set it to false . This example shows a table where the first column ID is completely hidden from view using the data-visible column attribute.

How to hide and show table column in javascript?

We create a function called 'hide_show_table()' to hide and show table column in this function we get the value of checkbox when clicked and check if the value is 'hide' it means we have to hide that particular table header and column and change that checkbox value to 'show' to show the hidden table header and column ...


2 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.

like image 173
Rex M Avatar answered Oct 19 '22 23:10

Rex M


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.

like image 39
DA. Avatar answered Oct 20 '22 01:10

DA.