user1475477 user1475477 - 6 months ago 9
jQuery Question

Filter table rows by link with jQuery

I searched around and couldn't find an exact solution to my problem, so here goes. I'm trying to filter the rows of a table by hiding unmatched rows by link click.

<a class="all">All: 314</a>
<a class="processing">Processing: 16</a>
<a class="completed">Completed: 12</a>
<a class="action">Action Required: 34</a>
<a class="errors">Errors: 6</a>


Here's an abbreviated version of the table:

<table id="batch">
<tr class="processing">Processing</tr>
<tr class="completed">Completed</tr>
<tr class="action">Action Required</tr>
<tr class="errors">Error</tr>


Here's the jQuery I'm using (tbody to avoid filtering the thead and some hidden rows):

$("a.processing").click(function(){
$("table#batch tbody tr:not(.processing)").fadeOut();
});

$("a.completed").click(function(){
$("table#batch tbody tr:not(.completed)").fadeOut();
});

$("a.action").click(function(){
$("table#batch tbody tr:not(.actionrequired)").fadeOut();
});

$("a.error").click(function(){
$("table#batch tbody tr:not(.error)").fadeOut();
});


The problem is that once you've filtered by one class, filtering again by another becomes impossible because all of the values except for the ones previously filtered are hidden. This happens with both
.fadeOut();
and
.hide();


I know there's a much simpler, less hacky way of accomplishing this, I just can't seem to get my head around it or get it to let me filter successively.

Answer

You can use $(this).attr('class') to select tr with same class as clicked a element

$('a').click(function() {
  $('#batch tr').hide();
  $('tr.' + $(this).attr('class') + '').show();
  if ($(this).attr('class') == 'all') $('table tr').show();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="all">All: 314</a>
<a class="processing">Processing: 16</a>
<a class="completed">Completed: 12</a>
<a class="action">Action Required: 34</a>
<a class="errors">Errors: 6</a>
<br>
<table id="batch">
  <tr class="processing"> <td>Processing</td></tr>
  <tr class="processing"> <td>Processing</td></tr>
  <tr class="processing"> <td>Processing</td></tr>
  <tr class="completed"> <td>Completed</td></tr>
  <tr class="completed"> <td>Completed</td></tr>
  <tr class="action"> <td>Action Required</td></tr>
  <tr class="errors"> <td>Error</td></tr>
</table>

Comments