How to filter/search a table
- Previous page Filter list
- Next page Filter elements
Learn how to use JavaScript to create filterable tables.
Filter the table
How to use JavaScript to search for specific data in a table.
Name | Country |
---|---|
Alfreds Futterkiste | Germany |
Berglunds snabbkop | Sweden |
Island Trading | UK |
Koniglich Essen | Germany |
Laughing Bacchus Winecellars | Canada |
Magazzini Alimentari Riuniti | Italy |
North/South | UK |
Paris specialites | France |
Create a filterable table
Step 1 - Add HTML:
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.."> <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> </table>
Step 2 - Add CSS:
Set the styles for the input element and the table:
#myInput { background-image: url('/css/searchicon.png'); /* Add a search icon to the input box */ background-position: 10px 12px; /* Position the search icon */ background-repeat: no-repeat; /* Do not repeat icon images */ width: 100%; /* Full width */ font-size: 16px; /* Increase font size */ padding: 12px 20px 12px 40px; /* Add some inner padding */ border: 1px solid #ddd; /* Add a gray border */ margin-bottom: 12px; /* Add some space below the input box */ } #myTable { border-collapse: collapse; /* Merge borders */ width: 100%; /* Full width */ border: 1px solid #ddd; /* Add a gray border */ font-size: 18px; /* Increase font size */ } #myTable th, #myTable td { text-align: left; /* Align text to the left */ padding: 12px; /* Add padding */ } #myTable tr { /* Add bottom border to all table rows */ border-bottom: 1px solid #ddd; } #myTable tr.header, #myTable tr:hover { /* Add grey background color to table header and when mouse hovers */ background-color: #f1f1f1; }
Step 3 - Add JavaScript:
<script> function myFunction() { // Declare variables var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); // Traverse all table rows and hide those that do not match the search query for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script>
Tip:If you want to perform a case-sensitive search, please remove toUpperCase()
.
Tip:If you want to search for country (index 1) instead of 'Name' (index 0), please set tr[i].getElementsByTagName('td')[0]
Change to [1].
Related pages
Tutorial:How to filter/search list
- Previous page Filter list
- Next page Filter elements