Проверка правильности работы txtValue === filter
.Обратите внимание, что, поскольку td
s не содержат слов, toUpperCase()
:
не требуется
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value;
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent;
if (txtValue.toUpperCase() === filter) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for counts">
<table id="myTable">
<tr class="header">
<th style="width:50%;">Counts</th>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>19</td>
</tr>
<tr>
<td>111</td>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>11</td>
</tr>
<tr>
<td>100</td>
</tr>
<tr>
<td>10</td>
</tr>
<tr>
<td>20</td>
</tr>
</table>
Если вы хотите отобразить все результаты, когда ввод пуст:
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value;
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent;
if (!filter || txtValue === filter) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for counts">
<table id="myTable">
<tr class="header">
<th style="width:50%;">Counts</th>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>19</td>
</tr>
<tr>
<td>111</td>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>11</td>
</tr>
<tr>
<td>100</td>
</tr>
<tr>
<td>10</td>
</tr>
<tr>
<td>20</td>
</tr>
</table>
Или, если быть более элегантным:
function myFunction() {
const { value } = document.querySelector('#myInput');
document.querySelectorAll('#myTable td').forEach((td) => {
td.parentElement.style.display =
(!value || td.textContent === value)
? ''
: 'none';
});
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for counts">
<table id="myTable">
<tr class="header">
<th style="width:50%;">Counts</th>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>19</td>
</tr>
<tr>
<td>111</td>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>11</td>
</tr>
<tr>
<td>100</td>
</tr>
<tr>
<td>10</td>
</tr>
<tr>
<td>20</td>
</tr>
</table>