I have 4 checkboxes to filter 4 categories of table data.
<input type="checkbox" value="audio" id="music_filter">
<input type="checkbox" value="video" id="video_filter">
<input type="checkbox" value="writing" id="writing_filter">
<input type="checkbox" value="game" id="games_filter">
<table>
<tr class="audio"> <td>some data</td> </tr>
<tr class="video"> <td>some data</td> </tr>
<tr class="writing"> <td>some data</td> </tr>
<tr class="game"> <td>some data</td> </tr>
</table>
Desired behaviors:
-
If no boxes are checked, display all table data
-
If any boxes are checked, hide any unchecked boxes
So far I have this but I don’t know how to find and hide the correct table rows:
$('#music_filter, #video_filter, #writing_filter, #games_filter').on('click',function(){
var unCheckedlength = $("input[type=checkbox]:not(:checked)").length;
if (unCheckedlength < 4) {
var notchecked = $("input[type=checkbox]:not(:checked)")
for (box in notchecked) {
// needed code to hide unwanted table rows
}
} else {
$('.audio, .writing, .game, .video').show();
};
});
2
Answers
You are on the right track. To achieve the desired behavior of showing and hiding the table rows based on the selected checkboxes, you can use the following approach:
Explanation:
$("input[type=checkbox]:checked")
to find all the checked checkboxes.map()
andget()
.$('tr').hide()
.$('.' + category).show()
to show the table rows that belong to that category (class).$('tr').show()
to display all table data.This code will ensure that only the table rows corresponding to the selected categories are shown, and the rest will be hidden. When no checkboxes are checked, all the table data will be displayed.
Each time an input is clicked this will get a list of checkboxes’ ids that are checked. Then it will hide all the rows that are not in that list.