Hide Table Columns with JavaScript

26 Feb 2006 by Dan,

Here is a little JavaScript function I whipped up last night. I’m working on a large loan-processing site, and thought it would be nice to be able to hide certain columns when viewing lots of loans on the same page. Here is the function:

function hideCol(strCol){
var ths = document.getElementsByTagName("th");
var tds = document.getElementsByTagName("td");
for (idx in ths){
if (ths[idx].className == strCol)
ths[idx].className = “hidden”;
}
for (idx in tds){
if (tds[idx].className == strCol)
tds[idx].className = “hidden”;
}
}

To use the function, just give each of the td’s and th’s in the column the same class name. Then add a link that calls “javascript:hideCol(’columnName’);”. You will also need to define a CSS rule “.hidden {display:none;}”.
This works especially well with scripted table building, such as dumping lots of rows from a database. It makes adding the class name much easier.

Downsides:

  1. The function only hides the column, once the classname has been changed to hidden, there is no way to display the columns, other than looking through table cells for those with the hidden class and removing it.
  2. The columns re-appear on a page refresh. The next logical step would be to use a cookie to store user the user’s preferences.

4 Comments

  1. Dan says:

    Update:
    I just discovered that browsers will support multiple classes, this will allow hiding and restore of colums all without a refresh, I’ll post an updated version of the function soon.

  2. Dan P. says:

    Abdinoor is god.

  3. Jerry Higbee says:

    Nice script - after searching for a couple of hours, I came upon this - easy to implement, easily explained, and perfect for my purpose. Thanks!

  4. Andy says:

    Hi

    Did you ever do the updated routine that will allow hiding and restore of colums all without a refresh

    Andy

Leave a Reply

More from Dan

Follow Me! Follow Me! Follow Me! Follow Me!
 
 
The Website Grade for www.abdinoor.com!