Filter Table Using JavaScript
The following example shows how to filter table rows by given input values. We can filter the rows using JavaScript function.
Example
<html> <head> <title>Table Filter Using JavaScript</title> <style> .container{ margin:0 auto; width:50%; } #filterTable{ border-collapse:collapse; width:100%; } #filterTable td,#filterTable th{ padding:5px; border:1px solid #ccc; } #filterSearch{ margin-bottom:5px; padding:5px; float:right; } </style> </head> <body> <div class='container'> <table id="filterTable"> <thead> <tr> <th style="width:60%;">Country</th> <th style="width:40%;">Capital City</th> </tr> </thead> <tbody> <tr> <td>Australia</td> <td>Canberra</td> </tr> <tr> <td>Brazil</td> <td>Brasilia</td> </tr> <tr> <td>Canada</td> <td>Ottawa</td> </tr> <tr> <td>India</td> <td>New Delhi</td> </tr> <tr> <td>Malaysia</td> <td>Kuala Lumpur</td> </tr> </tbody> </table> </div> <script> var table = document.querySelector("#filterTable"); var input=document.createElement("input"); input.setAttribute("id","filterSearch"); input.setAttribute("type","text"); input.setAttribute("placeholder","Search..."); table.parentNode.insertBefore(input,table); var td, txtValue; input.onkeyup=function(){ var filter = input.value.toUpperCase(); var tr = table.querySelector("tbody").querySelectorAll("tr"); for (let i = 0; i < tr.length; i++) { txtValue = tr[i].textContent || tr[i].innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } </script> </body> </html>Try it Yourself