使用基于HTML输入的Jquery过滤表数据

时间:2014-02-24 21:01:28

标签: javascript php jquery html

你能帮我正确地编写Jquery代码,这样我就可以根据文本输入过滤HTML表了。到目前为止,这是我的代码:

    <input type="text" name="inputdata" id="inputdata" onkeyup="filter()">
    <table>
            <tr>
                <th>ID</th>
                <th>Name</th>
            </tr>
            <tr name="data">
               <?php foreach ($products as $row) { ?>
                 <td><?php echo $row->id_product; ?></td>
                 <td><?php echo $row->name; ?></td>
               <?php }  ?>
            </tr>

Jquery代码

<script>
    function filter(){
        inp = $('#inputdata').val()
        $("tr").filter(function() {
            return $(this).text().indexOf(inp) == -1;
        }).hide();
    }
</script>

所以我的问题是:

  1. 搜索区分大小写
  2. 当我输入一些字符串时,让我们说Pants,Jquery过滤数据,但后来我必须刷新页面,所以我可以再次搜索。或者让我换一种方式......当我在搜索字段中删除输入的数据时,表格不会刷新。它只停留在裤子数据上,所以对于另一个搜索我必须重新加载网页
  3. 搜索数据时会删除
  4. <th>。如果我声明$('tr[name=data]').filter(function() {搜索停止工作
  5. 提前帮助我!

1 个答案:

答案 0 :(得分:3)

这应该解决你的问题:

<script>
function filter(){
    inp = $('#inputdata').val()
    // This should ignore first row with th inside
    $("tr:not(:has(>th))").each(function() {
        if (~$(this).text().toLowerCase().indexOf( inp.toLowerCase() ) ) {
            // Show the row (in case it was previously hidden)
            $(this).show();
        } else {
            $(this).hide();
        }
    });
}
</script>