Searching Only From td table not from Header (th)

时间:2018-03-31 07:35:55

标签: javascript jquery html css web

I can search from the entire table by using jquery and show only tr that match from search and it make header (th) gone. But i want it only search from table content. (Header stay and content that match show)

here my style

<style>
  td{border: 1px solid black}
</style>

here my html code

<input type="text" id="search" placeholder="Type to search">
<table id="tableAll">
  <tr>
     <th>Fruit name</th>
     <th>Color</th>
     <th>Notes</th>
  </tr>
   <tr>
      <td>Apple</td>
      <td>Green</td>
      <td>Delicious</td>
   </tr>
   <tr>
      <td>Grapes</td>
      <td>Green</td>
   </tr>
   <tr>
      <td>Orange</td>
      <td>Orange</td>
   </tr>
</table>

here my Script

var $rows = $('#tableAll tr');
$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

  $rows.show().filter(function() {
      var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
      return !~text.indexOf(val);
  }).hide();
});

you can also click here for code it in jsfiddle

2 个答案:

答案 0 :(得分:0)

一个非常简单的解决方案可能是查看

中的第二个tr
var $rows = $('#tableAll tr:gt(0)');
...

答案 1 :(得分:0)

其他答案肯定适用于您的具体情况,但我建议您使用<thead><tbody>来使用更清晰的HTML。

这样,如果您有多个标题,甚至是页脚(如果将它们放入<tfoot> s),代码也会起作用。

var $rows = $('#tableAll tbody tr');
$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

  $rows.show().filter(function() {
      var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
      return !~text.indexOf(val);
  }).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search" placeholder="Type to search">
<table id="tableAll">
  <thead>
    <tr>
       <th>Fruit name</th>
       <th>Color</th>
       <th>Notes</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Apple</td>
      <td>Green</td>
      <td>Delicious</td>
    </tr>
    <tr>
      <td>Grapes</td>
      <td>Green</td>
    </tr>
    <tr>
      <td>Orange</td>
      <td>Orange</td>
    </tr>
  </tbody>
</table>