This article introduces how to implement a table data search feature.

HTML code:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search..."> <table id="myTable"> <tr class="header"> <th style="width:60%;">Name</th> <th style="width:40%;">City</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> </table>

CSS code:

#myInput { background-image: url('https://static.jyshare.com/images/mix/searchicon.png'); /*Search button*/ background-position: 10px 12px; /*Position the search button*/ background-repeat: no-repeat; /*No-repeat image*/ 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 { /*Add border to the table*/ border-bottom: 1px solid #ddd; } #myTable tr.header, #myTable tr:hover { /*Add background to the table header and rows on mouse hover*/ background-color: #f1f1f1; }

JavaScript code:

function myFunction() { //Declare variables var input, filter, table, tr, td, i; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); //Loop through each table row and find matches 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"; } } } }

Tip:If you need case-sensitive matching, you can remove the toUpperCase() method.

Tip:If you need to search the second column (City), you can change tr[i].getElementsByTagName('td')[0]to[1]The index value starts from 0; i.e., 0 is the first column, 1 is the second column, and so on.

Online Demo