Search code examples
jqueryhtmlhtml-tableshow-hide

How to toggle specific multiple columns in a specific table in HTML using jQuery nth child selector?


I have a webpage where I show multiple tables. I would like to toggle the visibility of some columns of one specific table. I started using :

$(document).on("change","#includePaths",function() {
    $("td:nth-child(3)").toggle();
});    

when I had only one table.

Two questions :

  1. How to modify the above code so it adresses only one table (which is in <div id="mytable">...</div>) ?
  2. How to modify the above code so it toggles multiple columns based on a regex match on the table headers ?

Solution

  • I think you could try this:

    var regex_to_hide = /cool.*regex/;
    
    $(document).on("change", "#includePaths", function() {
      var columnsToHide = new Array();
    
      // I'm assuming #includePaths is the table
      // If not - replace "this" with the right selector for your table  
    
      // Test headers to see what we need to hide
      $("#mytable").find("th").each(function(i, th) {
          if (regex_to_hide.test($(th).html())) {
              columnsToHide.push(i);
          }
      });
    
      // Hide numbered columns
      for(i = 0; i < columnsToHide.lenght; i++) {
        $("#mytable").find("td:nth-child(" + columnsToHide[i] + ")").toggle();
      }
    });