Alexandre
Alexandre

Reputation: 13308

jQuery - how to filter a table row

I have a need to filter a certain table row by clicking a link.

function filterRows(statusName) {
         $("#mainTable > tbody > tr").find(statusName).each( function () {
             alert($(this));
             //the alert is not shown

         });
     }

<a class="rejected" href="#" onclick="filterRows('rejected');">rejected</a>
<a class="new" href="#" onclick="filterRows('new');">new</a>

<table id="mainTable">
  <thead>
   <tr>
     <td>col1</td>
     <td>col2</td>
   </tr>
 </thead>
 <tbody class="Content">
  <tr class="rejected">
    <td>data1</td>
    <td>data12</td>
  </tr>
  <tr>
    <td>data13</td>
    <td>data15</td>
  </tr>
  <tr  class="new">
    <td>data16</td>
    <td>data18</td>
  </tr>
</tbody>

But it's not working even alert($(this)) doesn't. Any suggestions?

Upvotes: 0

Views: 2537

Answers (3)

Tuanderful
Tuanderful

Reputation: 1319

I modified the selector as follows:

function filterRows(statusName) {
    $("#mainTable tbody tr."+statusName).each( function () {
        console.log(this);
        $(this).hide();
    });
}

Which can be further simplified to:

function filterRows(statusName) {
    $("#mainTable tbody tr."+statusName).hide();
}

Implementing a Filter

However, if you're trying to implement a jQuery filter based off data stored as classes, you can do something like:

function filterRows(statusName) {
    $("#mainTable tbody tr."+statusName).show();
    $("#mainTable tbody tr").not("."+statusName).hide();
}

This will show the rows that match the 'statusName', but equally important it will hide the rows that do not match. Remember to add functionality to clear filters!

Upvotes: 2

Alex Ball
Alex Ball

Reputation: 4474

or :

$('a').click(function(e){

    $('.'+e.target.className).not('a').hide();

});

Upvotes: 0

Scotty
Scotty

Reputation: 2510

Guy David is correct - change your HTML to read:

<table id="mainTable">
 <thead>
   <tr>
     <td>col1</td>
     <td>col2</td>
   </tr>
 </thead>
 <tbody>
  <tr class="rejected">
    <td>data1</td>
    <td>data12</td>
  </tr>
  <tr>
    <td>data13</td>
    <td>data15</td>
  </tr>
  <tr class="new">
    <td>data16</td>
    <td>data18</td>
  </tr>
 </tbody>
 ...

Upvotes: 0

Related Questions