Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a html table using dropdown colum list by jQuery

Tags:

html

jquery

mysql

I have a jQuery script that filters the html table having many columns, i just need to be able to show all the rows based on user input, but only want the filtering of the table should go through specific column selected by user from dropdown list

jQuery code

$(document).ready(function(){
   $("#kwd_search").keyup(function(){
      var term=$(this).val()
      if( term != "")
      {
        $("#my-table tbody>tr").hide();
        $("#my-table td").filter(function(){
               return $(this).text().toLowerCase().indexOf(term ) >-1
        }).parent("tr").show();
       $("#my-table tbody>tr th").show();
      }
      else
      {
        $("#my-table tbody>tr").show();
      }
   });
});

Html Code

<select id="clmn_name">
 <option>Column 1</option>
 <option>Column 2</option>
 <option>Column 3</option>
</select>

<input id="kwd_search" placeholder="Search Me">

<table id="my-table">
 <thead>
  <tr>
     <th>Column 1</th>
     <th>Column 2</th>
     <th>Column 3</th>
  </tr>
 </thead>
 <tbody>
  <tr>
    <td>Apple</td>
    <td>Orange</td>
    <td>Mango</td>
  </tr>

  <tr>
     <td>Strawberry</td>
     <td>Banana</td>
     <td>Cherry</td>
  </tr>
 </tbody>
</table>

So how can the returned HTML code be filtered as per the table column selected by user?

like image 438
Ankit Sharma Avatar asked May 19 '26 00:05

Ankit Sharma


1 Answers

You can use the selectedIndex property of the select element for filtering the target cells:

$("#kwd_search").keyup(function () {
    var index = $('#clmn_name').prop('selectedIndex'),
        term = $.trim(this.value);

    if (term.length === 0) {
        $("#my-table tbody > tr").show();
        return;
    }

    $("#my-table tbody > tr").hide().filter(function () {
        return this.cells[index].textContent.toLowerCase().indexOf(term) > -1;
    }).show();

});

In case that you want to listen to change event of the select element:

$(document).ready(function () {
    // Caching the elements and binding handlers
    var $s = $('#clmn_name').on('change', filterRows),
        $i = $("#kwd_search").on('keyup', filterRows),
        $rows = $("#my-table tbody > tr");

    function filterRows() {
        var ind = $s.prop('selectedIndex'),
            term = $.trim($i.val().toLowerCase());

        if (term.length === 0) return $rows.show();

        $rows.hide().filter(function () {
            return this.cells[ind].textContent.toLowerCase().indexOf(term) > -1;
        }).show();

    };
});

http://jsfiddle.net/jaeq6v0u/

The jQuerish way of selecting the target cells will be:

return $('td', this).eq(index).text().toLowerCase().indexOf(term) > -1;
like image 58
undefined Avatar answered May 20 '26 14:05

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!