Search code examples
javascripthtml-tableshow-hide

Javascript Hide Column by Default


After browsing online for tutorials on Javascript show/hide I could only find examples on where all the columns were by default visible. I'm looking for a way to have some columns hidden by default (and allow them to be toggled on via a checkbox) and to have some columns shown by default (and allow them to be toggled off via a checkbox).

Is this possible?

For reference my table structure is as follows:

<table>
  <thead>
<tr>
  <th>Name</th>
  <th>Job</th>
</tr>
  </thead>
  <tbody>
    <tr>
      <td>Mike</td>
      <td>Dancer</td>
    </tr>
  </tbody>
</table>

Solution

  • Pure javascript:

    HTML

    <input type="checkbox" onclick="showhide(1, this)" checked="checked" /> Name<br />
    <input type="checkbox" onclick="showhide(3, this)" checked="checked" /> Job<br />
    

    JS

    function showhide(column, elem){
        if (elem.checked)
            dp = "table-cell";
        else
            dp = "none";
        tds = document.getElementsByTagName('tr');
        for (i=0; i<tds.length; i++)
            tds[i].childNodes[column].style.display = dp;
    }
    

    Pure JS fiddle example

    Please consider using a javascript library as JQuery for such trivial things. You code could be as simple as:

    HTML

    <input type="checkbox" data-col="1" checked="checked" /> Name<br />
    <input type="checkbox" data-col="2" checked="checked" /> Job<br />
    

    jQuery JS:

    $(function(){
        $(':checkbox').on('change', function(){
            $('th, td', 'tr').filter(':nth-child(' + $(this).data('col') + ')').toggle();
        });
    });
    

    jQuery Fiddle example