Search code examples
javascriptcheckboxhtml-tablehideshow

Show/Hide more than one <table> with a checkbox


I want to show and hide several tables on one page with one button. Unfortunately my script can only show and hide one table at a time.

I have a page with a lot of queries. There are also text fields in a table. For a better overview, the tables with the text fields should only be displayed when the checkbox is ticked. The checkbox should not be clicked at the beginning.

function Displayer(n)
{
  var check = document.getElementById('Section'+n);
  if (check.style.display == 'none')
    {
      check.style.display='inline';
    }
    else
    {
      check.style.display='none';
    }
}
<p><input type="checkbox" class="btnstylega" onClick="Displayer(99)" />Show Tables</p>

<table id="Section99" style="display:none;"> <td>
AAAAAAAAAAAAAA
</td></table>

<table id="Section99" style="display:none;"> <td>
BBBBBBBBBBBBBBB
</td></table><br>

I want to show and hide many tables without adjusting the tables by clicking on the checkbox.


Solution

  • Improvement: It will add the event handler and trigger the change on load where needed

    Note the data-attribute on the checkbox

    var chg = new Event('change');
    document.querySelectorAll(".btnstylega").forEach(function(but) {
      but.addEventListener("change", function() {
        var checked = this.checked,
          section = this.getAttribute("data-tables");
        document.querySelectorAll('.Section' + section).forEach(function(sect) {
          sect.classList.toggle("hide",!checked);
        });
      })
      but.dispatchEvent(chg);
    });
    .hide {
      display: none;
    }
    <p><input type="checkbox" class="btnstylega" data-tables="88" checked />Show Tables 88 </p>
    <p><input type="checkbox" class="btnstylega" data-tables="99" />Show Tables 99</p>
    
    <table class="Section88">
    <tr>
      <td>
        AAAAAAAAAAAAAA
      </td>
      </tr>
    </table>
    
    <table class="Section88">
    <tr>
      <td>
        BBBBBBBBBBBBBBB
      </td>
      </tr>
    </table><hr>
    <table class="Section99">
    <tr>
      <td>
        CCCCCCCCCCCCCCCC
      </td>
      </tr>
    </table>
    
    <table class="Section99">
    <tr>
      <td>
        DDDDDDDDDDDDDDDDDDDD
      </td>
      </tr>
    </table>