jQuery Real Time Search - Remove Table Header Too

时间:2015-09-14 15:53:57

标签: javascript jquery html html-table

I am using the regular expression search code at this link, to allow real time search through a rather large table being populated server-side via php.

With a slight twist to the scenario describe in the above link, I am using table header tags to group (label) chunks of table row's together. I am preventing these table header row's from disappearing with the rest of the table row's so that when searching, the results are still nested in their group.

I would like the table header row's to disappear too, but only when there are no table row's between it and the next table header row. I'm not sure if counting row's will work, since the row's aren't gone, they're just hidden.

As an example, this is how my table is laid out:

HTML:

 <table>
  <tr>
     <th colspan="2">Group 1</th>
  </tr>
  <tr  class="searchable">
    <td>Record 1</td>
    <td>Record 2</td>
  </tr>
  <tr  class="searchable">
    <th>Group 2</th>
  </tr>
  <tr>
    <td>Record 3</td>
    <td>Record 4</td>
  </tr>
</table>

jQuery:

$( document ).ready(function() {
    var $rows = $('tr.searchable');

    $('#search').keyup(function(e) {

        if (e.keyCode == 27) { $(this).val("") }

        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();
    });
});

All help is appreciated!! Thanks!

2 个答案:

答案 0 :(得分:0)

我通过添加另一个类(每个组/标签都是唯一的)并在'.keyup()'部分中计算每个类的':visible'行来解决我的困境。一旦每个类中的行数下降到指定的数量以下,我在if语句中使用'.hide()'使表标题消失。 if语句的else方使用'.show()',如果类的数量超过指定的数量,则将表头恢复。

答案 1 :(得分:0)

我也遇到了这个问题,只需将.filter的主体部分作为目标,而不是将整个表作为目标即可解决。

$("#SearchPermissions").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#contentPart tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });

注意代码的$(“#contentPart tr”)部分。这是指 这样,标题就从搜索中排除了,因此在过滤表数据时仍会显示