Toggle Visibility of HTML Table Rows Based on Checkbox Values
I have found a great number of questions and answers regarding showing/hiding rows in a table based on checkboxes, but have failed to find an answer that I can get to work for my scenario.
My problem - I have an HTML table where each row has a checkbox that the user can flag if they find that row important. I would like to have a "master" checkbox that toggles the behavior of the table - if master is checked then only show the checked rows on the table, if master is unchecked then show all rows of the table. I need to accomplish this with pure JS, no JQuery.
Any help is greatly appreciated!
Here is some sample HTML code I've been using as a test...
<span class="text-default">
<input type="checkbox" class="down-checkbox" id="down" />
<label for="down">Check to show Flags only</label>
</span>
<table class="table1">
<thead>
<tr>
<th>Flag</th>
<th>No.</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" /> </td>
<td><span class="whatever">ONE</span></td>
</tr>
<tr>
<td><input type="checkbox" /> </td>
<td><span class="whatever">TWO</span></td>
</tr>
<tr>
<td><input type="checkbox" /> </td>
<td><span class="whatever">THREE</span></td>
</tr>
<tr>
<td><input type="checkbox" /> </td>
<td><span class="whatever">FOUR</span></td>
</tr>
</tbody>
</table>
Solution 1:
Here is an example
const rows = document.querySelectorAll(".table1 tbody tr")
document.getElementById("down").addEventListener("click",function() {
rows.forEach(row => row.hidden = this.checked && !row.querySelector("input").checked)
})
<span class="text-default">
<input type="checkbox" class="down-checkbox" id="down" />
<label for="down">Check to show Flags only</label>
</span>
<table class="table1">
<thead>
<tr>
<th>Flag</th>
<th>No.</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" /> </td>
<td><span class="whatever">ONE</span></td>
</tr>
<tr>
<td><input type="checkbox" /> </td>
<td><span class="whatever">TWO</span></td>
</tr>
<tr>
<td><input type="checkbox" /> </td>
<td><span class="whatever">THREE</span></td>
</tr>
<tr>
<td><input type="checkbox" /> </td>
<td><span class="whatever">FOUR</span></td>
</tr>
</tbody>
</table>