Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkboxes + Jquery hide/show

I have a series of a series of rows and checkboxes to filter them:

<ul> 
<li><input id="type-A" type="checkbox" checked="checked"> <a href="/A">A</a></li>
<li><input id="type-B" type="checkbox" checked="checked"> <a href="/B">B</a></li>
<li><input id="type-C" type="checkbox" checked="checked"> <a href="/C">C</a></li>
<li><input id="type-D" type="checkbox" checked="checked"> <a href="/D">D</a></li>
<li><input id="type-E" type="checkbox" checked="checked"> <a href="/E">E</a></li>
<li><input id="type-F" type="checkbox" checked="checked"> <a href="/F">F</a></li>
</ul>

<table>
<tr class="A">filler</tr>
<tr class="B">filler</tr>
<tr class="A B">filler</tr>
<tr class="C D">filler</tr>
<tr class="A F">filler</tr>
<tr class="A E F">filler</tr>
<tr class="F">filler</tr>
<tr class="C D E">filler</tr>
<tr class="A B C D E F">filler</tr>
</table>

I'd like to hide/show rows based on what is checked. Currently I'm using (with the help from this previous question: Use "this" to simplify code (simple jQuery) ):

$(function(){
  $("input[id^='type-']").change(function() {
    $("."+this.id.replace('type-','')).toggle(this.checked);
  }).change(); 
});

Which toggles what is shown every time a box is clicked and works great if each row only has one class. But they don't. How it's set up now, the order of clicking changes the rows that are shown. So I need to create a function that checks which checkboxes are checked and shows the rows that contain any of them. I'm not opposed to adding a button to make this happen.

I'd appreciate any help (and the direction to resources that could help me learn) you guys could give me!

like image 792
christina Avatar asked Feb 23 '26 23:02

christina


1 Answers

Modify the function to get a selector for all the checked check boxes.

$(function(){
  var $checkboxes = $("input[id^='type-']");
  $checkboxes.change(function() {
    var selector = '';
    $checkboxes.filter(':checked').each(function(){ // checked 
        selector += '.' + this.id.replace('type-','') + ', '; 
        // builds a selector like '.A, .B, .C, ' 
    });
    selector = selector.substring(0, selector.length - 2); // remove trailing ', '
    // tr selector
    $('table tr').hide() // hide all rows
       .filter(selector).show(); // reduce set to matched and show
  }).change(); 
});

EDIT: see jsfiddle

like image 167
Josiah Ruddell Avatar answered Feb 26 '26 11:02

Josiah Ruddell