Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Table Filter with Columns

I have set up a basic table from an example in SO here where I added column titles.

Can anyone make a suggestion how to fix the table filter so it does not hid the column titles? Here is the jsfiddle code I have been testing.

Javascript

var $rows = $('#table tr');
$('#search').keyup(function() {

var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
    reg = RegExp(val, 'i'),
    text;

$rows.show().filter(function() {
    text = $(this).text().replace(/\s+/g, ' ');
    return !reg.test(text);
}).hide();
});

Example search: If you type apple in the search - it hides title 1 and title 2. However, I prefer to keep the title 1 and title 2 after the search has been entered.

like image 243
Val Avatar asked Jun 10 '26 15:06

Val


2 Answers

My recommendation: add a class into your header, and exclude that from your filter results:

http://jsfiddle.net/7BUmG/1161/

    <input type="text" id="search" placeholder="Type to search">
    <table id="table">
         <tr class="header">
          <th>Title 1</th>
          <th>Title 2</th>
        </tr>    
        <tr>
          <td>Apple</td>
          <td>Green</td>
       </tr>
       <tr>
          <td>Grapes</td>
          <td>Green</td>
       </tr>
       <tr>
          <td>Orange</td>
          <td>Orange</td>
       </tr>
    </table>

And using RegEx

var $rows = $('#table tr[class!="header"]');
$('#search').keyup(function()
{
    
   var val = '^(?=.*\\b'  
                 + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') 
                 + ').*$',
                 reg = RegExp(val, 'i'),
                 text;
    
   $rows.show().filter(function() 
   {
      text = $(this).text().replace(/\s+/g, ' ');
      return !reg.test(text);
    }).hide();
});
like image 116
Howard Renollet Avatar answered Jun 13 '26 09:06

Howard Renollet


Use var $rows = $('#table tbody tr');

like image 29
jameslafferty Avatar answered Jun 13 '26 09:06

jameslafferty



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!