简体   繁体   English

使用Javascript搜索表格

[英]Using Javascript to search through tables

This is my very first post onto Stackoverflow. 这是我关于Stackoverflow的第一篇文章。 Happy to be here! 很高兴来到这里! I'm into my 8th week of internship at a company where I'm working on HTML, CSS, Jquery, Ajax, SQL. 我已经在一家从事HTML,CSS,Jquery,Ajax,SQL的公司实习了第八周。

Back when I started I was a newbie, but I'm getting the hang of it slowly. 回到我刚开始的时候,我还是一个新手,但是我慢慢地掌握了它。

I've run into something I don't know how to solve. 我遇到了我不知道该如何解决的问题。

My page displays the tables from a SQL database. 我的页面显示来自SQL数据库的表。 It also has a header with the categories. 它还具有带有类别的标题。

I've made the searchbar so that I can enter the ID, and it will then display the result live. 我已经创建了搜索栏,以便可以输入ID,然后它将实时显示结果。 What I actually want is to be able to search for everything. 我真正想要的是能够搜索所有内容。 So Id, client, certname,supplier_id, partner_nr etc. 因此ID,客户,证书名称,supplier_id,partner_nr等。

Does anyone know what I need to do? 有人知道我需要做什么吗?

Here is my code related to this portion: 这是我与这部分有关的代码:

**HTML: ** 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 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";
                    }
                }
            }
        }
    });

If you want to search the whole row then just change the for loop in your code to: 如果要搜索整行,则只需将代码中的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";
                    }

        }

No need to iterate through each td cell. 无需遍历每个td单元。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM