Skip to content
Advertisement

How can I filter the column type of the table using two buttons?

I want to filter the type column, one button filters the aquatic and in the other all except the aquatic

<button type="button" onclick="Aquatic()">Aquatic</button>    
<button type="button" onclick="NotAquatic()" >everything but aquatic</button>
<table class="table" >      
  <thead>
    <tr>                    
      <th scope="col">Animal</th>
      <th scope="col">Type </th>
    </tr>
  </thead>
  <tbody id="" >
    <tr>
      <td>bat</td>
      <td>aerial</td>
    </tr>
    <tr>
      <td>Fish</td>
      <td>Aquatic</td>
    </tr>
    <tr>
      <td>Horse</td>
      <td>Land</td>
    </tr>
    <tr>
      <td>Shark</td>
      <td>Aquatic</td>
    </tr>
    <tr>
      <td>Elephant</td>
      <td>Land</td>
    </tr>        
    <tr>
      <td>Whale</td>
      <td>Aquatic</td>
    </tr>
    <tr>
      <td>dove</td>
      <td>aerial</td>
    </tr>
  </tbody>
</table>

Advertisement

Answer

Hopefully this helps point you in the right direction! have a filterTable function which grabs all the table rows, and removes any inline style changes previously added to display. Then, I filter all the trs by the innerHTML content not including the term, and I take all those trs and set their display to none

function filterTable(aquaShown) {
  const trs = [...document.querySelectorAll("tbody tr")];
  trs.forEach(tr => tr.style.display = "");
  const hiddenTrs = aquaShown ? 
    trs.filter(tr => !tr.innerHTML.includes("Aquatic")) :
    trs.filter(tr => tr.innerHTML.includes("Aquatic"));
  hiddenTrs.forEach(tr => tr.style.display = "none");
}

function aquatic() {
  filterTable(true);
}

function nonaquatic() {
  filterTable(false);
}
<button type="button" onclick="aquatic()">Aquatic</button>
<button type="button" onclick="nonaquatic()">Non-Aquatic</button>
<table class="table">
    <thead>
        <tr>
            <th scope="col">Animal</th>
            <th scope="col">Type </th>
        </tr>
    </thead>
    <tbody id="">
        <tr>
            <td>Fish</td>
            <td>Aquatic</td>
        </tr>
        <tr>
            <td>Horse</td>
            <td>Land</td>
        </tr>
        <tr>
            <td>Shark</td>
            <td>Aquatic</td>
        </tr>
        <tr>
            <td>Elephant</td>
            <td>Land</td>
        </tr>
        <tr>
            <td>Whale</td>
            <td>Aquatic</td>
        </tr>
    </tbody>
</table>

EDIT refactored based on further clarification in comments

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement