I have an html script like below:
...
<h2>Invoice Registers</h2>
<table id="mytable" border="1">
<tr>
<th>Control Number</th><th>Payee Name</th>
<th>Workflow Step</th><th>Date Created</th>
</tr>
<tr>...my data...</tr>
<tr>...my data...</tr>
<tr>...my data...</tr>
</table>
...
What I want is to expand or collapse the entire HTML table when I click on "Invoice Registers" text.
If I had the <h2>
inside the table, I'd use the solution here and manage this, but couldn't find a solution for the current situation. How can I handle this? Note that the <h2>
tag must stay out of the table. Any help or advice would be appreciated.
Find the next table
after this h2
, and toggle it?
$('h2').click(function () {
$(this).nextAll('table').eq(0).toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Invoice Registers</h2>
<table border="1">
<tr>
<th>Control Number</th><th>Payee Name</th>
<th>Workflow Step</th><th>Date Created</th>
</tr>
</table>
<h2>Something else</h2>
<table border="1">
<tr>
<th>Control Number</th><th>Payee Name</th>
<th>Workflow Step</th><th>Date Created</th>
</tr>
</table>
Bonus
If you want an animation, wrap your tables in a div
(table
elements cannot be animated):
$('h2').click(function() {
$(this).nextAll('.table-wrapper').eq(0).slideToggle(400);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Invoice Registers</h2>
<div class="table-wrapper">
<table border="1">
<tr>
<th>Control Number</th><th>Payee Name</th>
<th>Workflow Step</th><th>Date Created</th>
</tr>
</table>
</div>
<h2>Something else</h2>
<div class="table-wrapper">
<table border="1">
<tr>
<th>Control Number</th><th>Payee Name</th>
<th>Workflow Step</th><th>Date Created</th>
</tr>
</table>
</div>