Skip to content

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.


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


<tr class="filter_1"><td>A</td></tr>
<tr class="filter_5"><td>B</td></tr>
<tr class="filter_1"><td>C</td></tr>


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.


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 = (num) {
    return '.filter_' + num
  var trs = $('table tbody tr') // select all the rows
  // if we have filters run the code
  if (filters.length) {
      .hide() // hide them
      .filter(filters) // find the rows with the class[es]
        .show() // show them
   } else {
     // no filters, just show everything
<script src=""></script>
<select multiple id="filterNumber">
  <option value="1">Option 1</option>
  <option value="3">Option 3</option>
  <option value="5">Option 5</option>
<button type="button" class="filterBtn">Filter</button>
    <tr class="filter_1">
    <tr class="filter_1">
    <tr class="filter_5">
    <tr class="filter_3">