使用Javascript搜索表格

问题描述 投票:1回答:1

这是我在Stackoverflow上的第一篇文章。很高兴来到这里!我正在一家公司实习的第8周,我正在从事HTML,CSS,Jquery,Ajax,SQL的工作。

回到我开始的时候,我是一个新手,但我慢慢地掌握它。

我遇到了一些我不知道如何解决的问题。

我的页面显示SQL数据库中的表。它还有一个带有类别的标题。

我已经创建了搜索栏,以便我可以输入ID,然后它会显示结果。我真正想要的是能够搜索一切。所以Id,client,certname,supplier_id,partner_nr等。

有谁知道我需要做什么?

这是我与此部分相关的代码:

** HTML:

<form class="form-inline my-2 my-lg-0" id="searchTable">
                <input class="form-control mr-sm-2" type="search" name="searchInput" placeholder="Search" aria-label="Search">
            </form>

Main.js

$("input[name=searchInput]").on('change keypress paste focus textInput input',function(){
        // Declare variables
        var input, filter, table, tr, td, i, x;
        input = $(this).val();
        filter = input.toUpperCase();
        table = document.getElementById("cfgAccounts");
        tr = table.getElementsByTagName("tr");

        // Loop through all table rows, and hide those who don't match the search query
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td");
            for (x = 0; x < td.length; x++) {
                td = tr[i].getElementsByTagName("td")[x];
                if (td) {
                    if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                        tr[i].style.display = "";
                    } else {
                        tr[i].style.display = "none";
                    }
                }
            }
        }
    });
javascript jquery html mysql
1个回答
0
投票

如果要搜索整行,只需将代码中的for循环更改为:

// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
            td = tr[i];
            if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                        tr[i].style.display = "";
                    } else {
                        tr[i].style.display = "none";
                    }

        }

无需遍历每个td单元格。

© www.soinside.com 2019 - 2024. All rights reserved.