Filter table rows with jquery

2020-03-09 07:05发布

I would like to know how to filter table rows based on a column value. Plugins excluded, I would like to figure it out how to make this thing to work.

3条回答
我想做一个坏孩纸
2楼-- · 2020-03-09 07:40

Here's another example of filtering table rows. Turning the filter value and the table row text lowercase makes the filter case insensitive.

$(function() {
  $("#filter").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#example-table > tbody > tr").filter(function() {      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
  <div class="form-group">
    <label for="filter">Filter:</label> <input type="text" id="filter">
  </div>
  <table id="example-table">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Bob</td>
        <td>Smith</td>
        <td>50</td>
      </tr>
      <tr>
        <td>Jenny</td>
        <td>Smith</td>
        <td>51</td>
      </tr>
      <tr>
        <td>Mike</td>
        <td>Smithers</td>
        <td>52</td>
      </tr>
    </tbody>
  </table>
</body>
</html>

查看更多
成全新的幸福
3楼-- · 2020-03-09 07:42

The basic idea behind all table-filtering is to hide all rows and then show those where the content of a <td> has the searchstring included.

With jQuery the magic is done like this:

$('tr').filter(":contains('" + searchstring + "')").show();

But there's no need to use jQuery for this - I've coded a plain JS-solution for it. You can find it here.

查看更多
Lonely孤独者°
4楼-- · 2020-03-09 07:44

Your question is quite vague, but the general idea would be something like this:

$("td").filter(function() {
    return $(this).text().indexOf("whatever") !== -1;
}).parent().remove();

Here's a working example. It first selects all table cells, then filters them based on some text, and removes the parent (which should be the tr) of any remaining rows.

If you don't care about individual columns, you can select the tr elements and get rid of the call to parent. That will still work because text will return the text of all the children of the selected tr.

Update based on comments

The above will remove the matching table rows from the DOM completely. If you want to just hide them, you can replace remove with hide. If you then wanted to make the rows visible again you could simply do something like:

$("tr").show();

Which selects all the tr elements and shows them (ones that are already visible will not be affected, so just the ones previously hidden will become visible again).

查看更多
登录 后发表回答