I have a table with 20 columns and about a thousand rows. I want to show/hide different columns based on filters, i.e. each filter displays columns that are relevant to that filter and hides columns that aren't.
I have tried two approaches:
1) Add a "hide" class to the THs and TDs based on the index of the column using jQuery. This is incredibly slow as the class has to be added to each table cell to be hidden.
2) Add a "hide" class to the COLs within a COLGROUP at the top of the table. The problem here is that when style rules like "display: none" or "visibility: collapse" are added to COLs, not all browsers apply those rules to the corresponding columns within the table because the cells are not children of COLs.
Any suggestions?
To hide whole columns you can use a stacking definition:
// HTML
<table id="my-table" class="no-filter">
<tr>
<td class="column column1">c1</td>
<td class="column column2">c2</td>
<td class="column column3">c3</td>
</tr>
// etc x1000
</table>
// CSS
table td.column { display: none; } /* by default all columns are hidden */
table.no-filter td.column { display: block; } /* no-filter shows _all_ columns */
table.filter1 td.column1 { display: block; }
table.filter2 td.column2 { display: block; }
table.filter3 td.column3 { display: block; }
If you want to show just column1:
$("#my-table").removeClass("no-filter").addClass("filter1");
If you want to show column1 and column3:
$("#my-table").removeClass("no-filter").addClass("filter1").addClass("filter3");
If you need one-to-many filters
table.filter4 td.column4,
table.filter4 td.column5,
table.filter4 td.column99 { display: block; }
/* filter 4 shows column 4 5 and 99 */
Filters can overlap:
table.filter5 td.column5 { display: block; }
table.filter6 td.column5,
table.filter6 td.column6 { display: block; }
This assumes your filters are pre-defined and you know the filter-to-column mapping.
Minor note: I haven't tested this, there might be precedence issues. If the filters aren't applying properly change td.columnX
to td.column.columnX
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With