过滤表格多列

时间:2017-04-25 22:38:57

标签: javascript html filter html-table

我在我的页面上使用了w3School代码并且它工作正常,但它只过滤了一列,不知道如何创建循环但跳过那里更容易解决。

    td = tr[i].getElementsByTagName("td")[0];     

更改此处0到1更改列,可以找到任何事情,所以尝试了许多不同的东西但不是程序员不知道是否有任何其他属性允许多列,花了这么多搜索,请帮助



function myFunction() {
  var input, filter, table, tr, td, i;
  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")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
&#13;
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myTable {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ddd;
  font-size: 18px;
}

#myTable th,
#myTable td {
  text-align: left;
  padding: 12px;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
}

#myTable tr.header,
#myTable tr:hover {
  background-color: #f1f1f1;
}
&#13;
<h2>My Customers</h2>

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search             for names.." title="Type in a name">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Koniglich Essen</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td>North/South</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Paris specialites</td>
    <td>France</td>
  </tr>
</table>
&#13;
&#13;
&#13;

14 个答案:

答案 0 :(得分:23)

网络上有significantly better个资源,而不是W3学校,你真的应该避开网站IMO。话虽如此,如果你想匹配整行,你只需要查看tr而不是td中的一个:

function myFunction() {
    var input = document.getElementById("myInput");
    var filter = input.value.toUpperCase();
    var table = document.getElementById("myTable");
    var tr = table.getElementsByTagName("tr");
    for (var i = 0; i < tr.length; i++) {
        if (tr.textContent.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
        } else {
            tr[i].style.display = "none";
        }      
    }
}

如果要过滤多个列而不是整行,只需在条件中使用OR(||):

function myFunction() {
    var input = document.getElementById("myInput");
    var filter = input.value.toUpperCase();
    var table = document.getElementById("myTable");
    var tr = table.getElementsByTagName("tr");
    var tds = tr.getElementsByTagName('td');

    for (var i = 0; i < tr.length; i++) {
        var firstCol = tds[0].textContent.toUpperCase();
        var secondCol = tds[1].textContent.toUpperCase();
        if (firstCol.indexOf(filter) > -1 || secondCol.indexOf(filter) > -1) {
            tr[i].style.display = "";
        } else {
            tr[i].style.display = "none";
        }      
    }
}

本教程不太好的一些原因:您应该避免使用innerHTML而应使用textContent,因为您的单元格可能包含HTML,并且用户可以在尝试时键入标记名称搜索可见文本并被匹配的东西搞糊涂。您应该提供表明其功能的功能名称(例如filterTable而不是myFunction)。此外,还有更简单的方法来访问表数据(例如tr.cells)。如果向keyup添加#myInput事件侦听器,则每次调用该函数时都不需要查找该DOM节点。这是一个例子:

function filterTable(event) {
    var filter = event.target.value.toUpperCase();
    var rows = document.querySelector("#myTable tbody").rows;
    
    for (var i = 0; i < rows.length; i++) {
        var firstCol = rows[i].cells[0].textContent.toUpperCase();
        var secondCol = rows[i].cells[1].textContent.toUpperCase();
        if (firstCol.indexOf(filter) > -1 || secondCol.indexOf(filter) > -1) {
            rows[i].style.display = "";
        } else {
            rows[i].style.display = "none";
        }      
    }
}

document.querySelector('#myInput').addEventListener('keyup', filterTable, false);
<input id="myInput" type="text" />
<table id="myTable">
 <thead>
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
 </thead>
 <tbody>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Koniglich Essen</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td>North/South</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Paris specialites</td>
    <td>France</td>
  </tr>
 </tbody>
</table>

答案 1 :(得分:1)

您的代码很好。要添加多列,您需要添加||条件(在 if 子句中)。

Rob答案的问题是,如果您使用 tr ,它将过滤掉表格标题。

这是代码的扩展名:

function myFunction() {
var input, filter, table, tr, td, i;
  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")[0]; // for column one
     td1 = tr[i].getElementsByTagName("td")[1]; // for column two
/* ADD columns here that you want you to filter to be used on */
    if (td) {
      if ( (td.innerHTML.toUpperCase().indexOf(filter) > -1) || (td1.innerHTML.toUpperCase().indexOf(filter) > -1) )  {            
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
} 

答案 2 :(得分:1)

添加||并在if语句完全起作用的情况下添加新条件。

function myFunction() {
var input, filter, table, tr, td, i;
  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")[0]; // for column one
     td1 = tr[i].getElementsByTagName("td")[1]; // for column two
/* ADD columns here that you want you to filter to be used on */
    if (td) {
      if ( (td.innerHTML.toUpperCase().indexOf(filter) > -1) || (td1.innerHTML.toUpperCase().indexOf(filter) > -1) )  {            
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
} 
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myTable {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ddd;
  font-size: 18px;
}

#myTable th,
#myTable td {
  text-align: left;
  padding: 12px;
}

#myTable tr {
  border-bottom: 1px solid #ddd;
}

#myTable tr.header,
#myTable tr:hover {
  background-color: #f1f1f1;
}
<h2>My Customers</h2>

<input type="text" id="myInput" onkeyup="myFunction()" 
placeholder="Search for names.." title="Type in a name">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Koniglich Essen</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td>North/South</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Paris specialites</td>
    <td>France</td>
  </tr>
</table>

答案 3 :(得分:0)

你只需要添加另一个循环来遍历单元格,所以:

public class Functions
{
    public static void HandleMessage(
        [QueueTrigger("my-queue")] string message,
        TextWriter log
    )
    {
        // Long running process
        ...

答案 4 :(得分:0)

根据您所遵循的相同教程,接收三个不同的文本输入并相应地对行中的所有内容进行排序:

function SortByMultiple() {

    //Declare needed variables
    var dateInput, nameInput, locationInput, dateFilter, nameFilter, locationFilter, table, tr, tdN, tdD, tdL, i;

    //Set inputs by getElementById
    nameInput = document.getElementById('nameInput');
    dateInput = document.getElementById('dateInput');
    locationInput = document.getElementById('locationInput');
    //Set filters
    nameFilter = nameInput.value.toUpperCase();
    dateFilter = dateInput.value.toUpperCase();
    locationFilter = locationInput.value.toUpperCase();
    //Set the table and tr variables
    table = document.getElementById("UL");
    tr = document.getElementsByTagName("tr");

    //Loop through items and hide those that don't match the query -->
    for (i = 0; i < tr.length; i++) {

        //Name is at index 0
        tdN = tr[i].getElementsByTagName("td")[0];
        //Date is at index 2
        tdD = tr[i].getElementsByTagName("td")[2];
        //Location is at index 1
        tdL = tr[i].getElementsByTagName("td")[1];

        if (tdN.innerHTML.toUpperCase().indexOf(nameFilter) > -1 && tdD.innerHTML.toUpperCase().indexOf(dateFilter) > -1 && tdL.innerHTML.toUpperCase().indexOf(locationFilter) > -1) {
            tr[i].style.display = "";
        }
        else {
            tr[i].style.display = "none";
        }
    }

}

通过AND设置彼此之后的条件,它们都将在过滤器中被考虑在内!

答案 5 :(得分:0)

将此JQuery添加到文件的head标记中。 #myinput是id搜索框,它是文本类型的输入元素。 #tab-id是tbody的ID,因此您应该将表明确分为thead和tbody

<script>
    $(document).ready(function(){
        $("#myInput").on("keyup", function() {
            var value = $(this).val().toLowerCase();
            $("#tab-id tr").filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
            });
        });
    });
</script>

答案 6 :(得分:0)

此解决方案适用于具有多个值的多列过滤器

The empty text boxes is to type your value to filter

所有文本框的类名称均为'.filter_rep'

  $(document).on('keyup','.filter_rep',function () {
    var $this = $(this).val();
    var val_array = [];
    var id_array = [];

    $('.filter_rep').each(function () {
        thisval = $(this).val();
        id = '.'+$(this).attr('id');
        if (thisval){
            id_array.push(id);
            val_array.push(thisval);
        }
    });
    // using val_array to check all the columns and hide
    if(val_array.length > 0){
        $('tr').each(function () {
            $(this).show();
        });
        for (i=0;i<val_array.length;i++){
            $(id_array[i]).each(function () {
                if (!($(this).text().toLowerCase().indexOf(val_array[i]) > -1)){
                    $(this).parent().hide();
                }
            });
        }
    }else{
        $('tr').each(function () {
          $(this).show();
        });
    }
})

});

  

如果有任何疑问可查我!

答案 7 :(得分:0)

我只是使用了开始时使用的相同的W3代码,所以我发现了这个相当优雅的解决方案-应该适用于大量列

    function myFunction() {
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("mainTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    td2 = tr[i].getElementsByTagName("td")[1];
    if (td || td2) {
      txtValue = td.textContent || td.innerText;
      txtValue2 = td2.textContent || td2.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1 || txtValue2.toUpperCase().indexOf(filter) > -1 ) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }       
  }
}

答案 8 :(得分:0)

用于动态过滤多列的代码。无需更改。

    function myFunction(elem) {
        var input, filter, table, tr, td, i, txtValue;
        input = elem;
        filter = input.value.toUpperCase();
        table = document.getElementById("YourTableId");
        tr = table.getElementsByTagName("tr");
        for (i = 1; i < tr.length; i++) {
            tds = tr[i].getElementsByTagName("td");
            var matches = false;

            for (j = 0; j < tds.length; j++) {
                if (tds[j]) {
                    txtValue = tds[j].textContent || tds[j].innerText;
                    if (txtValue.toUpperCase().indexOf(filter) > -1) {
                        matches = true;
                    } 
                }
            }

            if(matches == true)
            {
                tr[i].style.display = "";
            }
             else {
                    tr[i].style.display = "none";
                }

            }
        }

答案 9 :(得分:0)

使用以下代码增强Rob.M的答案,以适合多列搜索。

function filterTable(event) {
//Convert search value to uppercase and assign the value to variable 'filter'
var filter = event.target.value.toUpperCase();
//Find total rows in the table's body
var rows = document.querySelector("#table tbody").rows;
//Start looping rows
for (var i = 0; i < rows.length; i++) {
    //Count the columns in current row
    var colCount = $("#table th").length;
    //Assign a variable 'res' for result counting
    var res = 1;
    //Start looping columns in current row
    for (let j = 0; j < colCount; j++) {
        //Iterate single cell and convert the contents to uppercase, assign the content to variable 'x'
        var x = "col_" + j;
        var x = rows[i].cells[j].textContent.toUpperCase();
        //find the position of first index of the search value.
        //If search value found ADD 1 to 'res' else LESS 1
        x.indexOf(filter) > -1 ? res++ : res--;
    }
    //Convert the colCount variable to absolute value
    colCount = -Math.abs(colCount - 1);
    //Display or hide the row, based on result condition
    res > colCount || filter == "" ? (rows[i].style.display = "") : (rows[i].style.display = "none");
}

}

答案 10 :(得分:0)

我将代码上传到此处以在两列之间搜索表格数据

function searching() {
    var input, filter, table, tr, td1, td2, i, txtValue;
    input = document.getElementById("search");
    filter = input.value.toUpperCase();
    table = document.getElementById("table");
    tr = table.getElementsByTagName("tr");

    for (i = 0; i < tr.length; i++) { 
        td1 = tr[i].getElementsByTagName("td")[0];
        td2 = tr[i].getElementsByTagName("td")[1];
        if (td1 || td2) {
            txtValue1 = td1.textContent || td1.innerText;
            txtValue2 = td2.textContent || td2.innerText;
            if (txtValue1.toUpperCase().indexOf(filter) > -1 || (txtValue2.toUpperCase().indexOf(filter) > -1)) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
}


<input class="form-control my-3" id="search" onkeyup="searching()" type="search" placeholder="Search To-Do items here..." aria-label="Search">


<table class="table my-5">
    <thead class="thead-dark">
        <tr>
            <th scope="col ">Sr No.</th>
            <th scope="col ">Item</th>
            <th scope="col ">Description</th>
            <th scope="col ">Manage</th>
        </tr>
    </thead>
    <tbody id="table">
    </tbody>
</table>

答案 11 :(得分:0)

这是正确的功能

function myFunction() {
    var input = document.getElementById("myInput");
    var filter = input.value.toUpperCase();
    var table = document.getElementById("myTable");
    var tr = table.getElementsByTagName("tr");
    for (var i = 0; i < tr.length; i++) {
        if (tr[i].textContent.toUpperCase().indexOf(filter) > -1) {
            tr[i].style.display = "";
        } else {
            tr[i].style.display = "none";
        }      
    }
}

应为 tr[i].textContent

答案 12 :(得分:-1)

function filterTable(event) {
    var filter = event.target.value.toUpperCase();
    var rows = document.querySelector("#myTable tbody").rows;
    
    for (var i = 0; i < rows.length; i++) {
        var firstCol = rows[i].cells[0].textContent.toUpperCase();
        var secondCol = rows[i].cells[1].textContent.toUpperCase();
        if (firstCol.indexOf(filter) > -1 || secondCol.indexOf(filter) > -1) {
            rows[i].style.display = "";
        } else {
            rows[i].style.display = "none";
        }      
    }
}

document.querySelector('#myInput').addEventListener('keyup', filterTable, false);
<input id="myInput" type="text" />
<table id="myTable">
 <thead>
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
 </thead>
 <tbody>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Koniglich Essen</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Italy</td>
  </tr>
  <tr>
    <td>North/South</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Paris specialites</td>
    <td>France</td>
  </tr>
 </tbody>
</table>

答案 13 :(得分:-1)

从本文中借用代码我可以使用||在2列上进行过滤(或)运算符。但是,我希望能够使用&&(And)运算符进行过滤。

我多次尝试均未成功。我可以帮忙。

<script>
function myFunction() {
  var input0, input1, filter0, filter1, table, tr, td, cell, i, j;
  document.getElementById("myInput0").value = 'Female';
  document.getElementById("myInput1").value = 'Engineering';
  input0 = document.getElementById("myInput0");
  input1 = document.getElementById("myInput1");
  filter0 = input0.value.toUpperCase();
  filter1 = input1.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 1; i < tr.length; i++) {
    // Hide the row initially.
  tr[i].style.display = "none";

  td = tr[i].getElementsByTagName("td");
    for (var j = 0; j < td.length; j++) {
      cell = tr[i].getElementsByTagName("td")[j];
      if (cell) {
         if (cell.textContent.toUpperCase().indexOf(filter0)>-1 || 
    cell.textContent.toUpperCase().indexOf(filter1)>-1) {
          tr[i].style.display = "";
          break;
        } 
      }
    }
  }
}
</script>

<body>
<input type="text" id="myInput0">
<input type="text" id="myInput1">
<input type='button' onclick='myFunction()' value='click me' />

<table id="myTable">
  <thead>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Gender</th>
    <th>Department</th>
  </tr>
  </thead>
  <tbody>
  <tr>
    <td>John</td>
    <td>Doe</td>
    <td>Male</td>
    <td>Sales</td>
  </tr>
  <tr>
    <td>Mary</td>
    <td>Moe</td>
    <td>Female</td>
    <td>Service</td>
  </tr>
  <tr>
    <td>July</td>
    <td>Dooley</td>
    <td>Female</td>
    <td>Service</td>
  </tr>
  <tr>
    <td>Anja</td>
    <td>Ravendale</td>
    <td>Female</td>
    <td>Engineering</td>
  </tr>
  <tr>
    <td>Thomas</td>
    <td>Dubois</td>
    <td>Male</td>
    <td>Sales</td>
  </tr>
  <tr>
    <td>Deidre</td>
    <td>Masters</td>
    <td>Female</td>
    <td>Sales</td>
  </tr>
  <tr>
    <td>Sean</td>
    <td>Franken</td>
    <td>Male</td>
    <td>Engineering</td>
  </tr>
  </tbody>
</table>

</body>