How to perform a real time search and filter on a HTML table

I've been Googling and searching Stack Overflow for a while, but I just can't get around this problem.

I have a standard HTML table, containing, say, fruit. Like so:

<table>
   <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>

Above this I have a text box, which I would like to search the table as a user types. So, if they type Gre for example, the Orange row of the table would disapear, leaving the Apple and Grapes. If they carried on and typed Green Gr the Apple row should disapear, leaving just grapes. I hope this is clear.

And, should the user delete some or all of their query from the text box, I should like all of the rows that now match the query to reappear.

While I know how to remove a table row in jQuery, I have little idea about how to go about doing the search and removing rows selectively based on this. Is there a simple solution to this? Or a plugin?

If anyone could point me in the right direction it would be brilliant.

Thank you.


I created these examples.

Simple indexOf search

var $rows = $('#table 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();
});

Demo : http://jsfiddle.net/7BUmG/2/

Regular expression search

More advanced functionality using regular expressions will allow you to search words in any order in the row. It will work the same if you type apple green or green apple :

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

Demo : http://jsfiddle.net/dfsq/7BUmG/1133/

Debounce

When you implement table filtering with search over multiple rows and columns it is very important that you consider performance and search speed/optimisation. Simply saying you should not run search function on every single keystroke, it's not necessary. To prevent filtering to run too often you should debounce it. Above code example will become:

$('#search').keyup(debounce(function() {
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
    // etc...
}, 300));

You can pick any debounce implementation, for example from Lodash _.debounce, or you can use something very simple like I use in next demos (debounce from here): http://jsfiddle.net/7BUmG/6230/ and http://jsfiddle.net/7BUmG/6231/.


i have an jquery plugin for this. It uses jquery-ui also. You can see an example here http://jsfiddle.net/tugrulorhan/fd8KB/1/

$("#searchContainer").gridSearch({
            primaryAction: "search",
            scrollDuration: 0,
            searchBarAtBottom: false,
            customScrollHeight: -35,
            visible: {
                before: true,
                next: true,
                filter: true,
                unfilter: true
            },
            textVisible: {
                before: true,
                next: true,
                filter: true,
                unfilter: true
            },
            minCount: 2
        });

这里是在HTML表格中搜索最好的解决方案,同时覆盖所有表格表格中的所有td,tr), 纯javascript和尽可能的代码:

<input id='myInput' onkeyup='searchTable()' type='text'>

<table id='myTable'>
   <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>

<script>
function searchTable() {
    var input, filter, found, table, tr, td, i, j;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    table = document.getElementById("myTable");
    tr = table.getElementsByTagName("tr");
    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td");
        for (j = 0; j < td.length; j++) {
            if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
                found = true;
            }
        }
        if (found) {
            tr[i].style.display = "";
            found = false;
        } else {
            tr[i].style.display = "none";
        }
    }
}
</script>
链接地址: http://www.djcxy.com/p/74970.html

上一篇: JavaScript中“〜”的含义是什么?

下一篇: 如何在HTML表格上执行实时搜索和过滤