Created
June 12, 2024 01:14
-
-
Save bmcculley/f1d06784496336d4118f382537e08029 to your computer and use it in GitHub Desktop.
Filter HTML Table By Multiple Columns https://hakk.dev/blog/posts/html-table-filter/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<!-- https://hakk.dev/blog/posts/html-table-filter/ --> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Table Filter</title> | |
<style> | |
table { | |
border-collapse: collapse; | |
width: 100%; | |
} | |
th, td { | |
border: 1px solid #dddddd; | |
padding: 8px; | |
text-align: left; | |
} | |
tr:nth-child(even) { | |
background-color: #f2f2f2; | |
} | |
input[type=text] { | |
width: 100%; | |
padding: 8px; | |
margin-top: 6px; | |
margin-bottom: 16px; | |
border: 1px solid #ccc; | |
border-radius: 4px; | |
box-sizing: border-box; | |
} | |
</style> | |
</head> | |
<body> | |
<h2>Table Filter</h2> | |
<input type="text" id="myInput" onkeyup="filterTable()" placeholder="Search for names, countries, or cities.."> | |
<table id="myTable"> | |
<thead> | |
<tr> | |
<th>Name</th> | |
<th>Country</th> | |
<th>City</th> | |
</tr> | |
</thead> | |
<tbody> | |
<tr> | |
<td>John</td> | |
<td>USA</td> | |
<td>New York</td> | |
</tr> | |
<tr> | |
<td>Mary</td> | |
<td>UK</td> | |
<td>London</td> | |
</tr> | |
<tr> | |
<td>Peter</td> | |
<td>Canada</td> | |
<td>Toronto</td> | |
</tr> | |
<tr> | |
<td>Anna</td> | |
<td>Germany</td> | |
<td>Berlin</td> | |
</tr> | |
<tr> | |
<td>Michael</td> | |
<td>Australia</td> | |
<td>Sydney</td> | |
</tr> | |
</tbody> | |
</table> | |
<script> | |
function filterTable() { | |
var input, filter, table, tr, td, i, txtValue; | |
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"); | |
for (var j = 0; j < td.length; j++) { | |
txtValue = td[j].textContent || td[j].innerText; | |
if (txtValue.toUpperCase().indexOf(filter) > -1) { | |
tr[i].style.display = ""; | |
break; | |
} else { | |
tr[i].style.display = "none"; | |
} | |
} | |
} | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment