Search code examples
javascriptjqueryhtmlarraystablefilter

jQuery - Filtering table rows using an array of class names


I have a table with some values and a filter option where the user can select multiple values and filter the table. What I am trying to achieve is to have a filter with numbers from 1 to 10, and table tr with class names filter_1, filter_2, filter_3 etc. when I choose number 1 from filter and click on it, it will show only tr with class filter_1. My code is below.

HTML:

<select multiple id="filterNumber">
<option value="1">1</option><option value="1">2</option><option value="1">3</option>
</select>
<button class="filterBtn">Filter</button>

Table:

<table>
<thead><tr><th>Name</th></tr></thead>
<tbody>
<tr class="filter_1"><td>A</td></tr>
<tr class="filter_5"><td>B</td></tr>
<tr class="filter_1"><td>C</td></tr>
</thead>
</table>

jQuery:

$(document).on('click','.filterBtn',function(){
let filterNumber = $('#filterNumber).val();

//loop through this numbers and hide tr without this class name 
});

I know how to pass these values through AJAX into DB and display the result, but I am trying to learn more like doing from the front-end only that makes my app more faster. But I don't know how to filter this using JavaScript or jQuery.


Solution

  • Select all the thdboy rows and hide them. Select all the rows with the class and show them

    $(document).on("click", '.filterBtn', function() {
    
      const filterNumber = $('#filterNumber').val();
    
      // create a comma seperated list of the class names to show
      var filters = filterNumber.map(function (num) {
        return '.filter_' + num
      }).join()
      
      var trs = $('table tbody tr') // select all the rows
    
      // if we have filters run the code
      if (filters.length) {
        trs
          .hide() // hide them
          .filter(filters) // find the rows with the class[es]
            .show() // show them
       } else {
         // no filters, just show everything
         trs.show()
       }
    
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select multiple id="filterNumber">
      <option value="1">Option 1</option>
      <option value="3">Option 3</option>
      <option value="5">Option 5</option>
    </select>
    <button type="button" class="filterBtn">Filter</button>
    
    
    <table>
      <thead>
        <tr>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>
        <tr class="filter_1">
          <td>A1</td>
        </tr>
        <tr class="filter_1">
          <td>A2</td>
        </tr>
        <tr class="filter_5">
          <td>B</td>
        </tr>
        <tr class="filter_3">
          <td>C</td>
        </tr>
        </tbody>
    </table>