Skip to content

Commit 334c724

Browse files
authored
filterTable.js
Create a filtered table without third-party libraries, just pure Javascript Filter/Search Table
1 parent eb91639 commit 334c724

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

filterTable.js

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
//HTML SECTION
3+
<html>
4+
<input type="text" id="filter_input" placeholder="Some descriptive text...">
5+
<div id="table_div"></div>
6+
</html>
7+
8+
//Some CSS style for example
9+
#filter_input {
10+
background-image: url('/css/searchicon.png'); /* Add a search icon to input */
11+
background-position: 10px 12px; /* Position the search icon */
12+
background-repeat: no-repeat; /* Do not repeat the icon image */
13+
width: 100%; /* Full-width */
14+
font-size: 16px; /* Increase font-size */
15+
padding: 12px 20px 12px 40px; /* Add some padding */
16+
border: 1px solid #ddd; /* Add a grey border */
17+
margin-bottom: 12px; /* Add some space below the input */
18+
}
19+
*/
20+
//JAVASCRIPT INIT
21+
document.getElementById("filter_input").addEventListener("keyup", function(){
22+
appendFilter("filter_input", "table_div")
23+
});
24+
25+
26+
function appendFilter(element, table) => {
27+
var input, filter, table, tr, td, i, txtValue;
28+
29+
input = document.getElementById(element);
30+
filter = input.value.toUpperCase();
31+
table = document.getElementById(table);
32+
tr = table.getElementsByTagName("tr");
33+
34+
// Loop through all table rows except header, and hide those who don't match the search query
35+
// You can modify "i" to zero in order of you table structure
36+
for (i = 1; i < tr.length; i++) {
37+
td = tr[i].getElementsByTagName("td")[0];
38+
if (td) {
39+
txtValue = td.textContent || td.innerText;
40+
if (txtValue.toUpperCase().indexOf(filter) > -1) {
41+
tr[i].style.display = "";
42+
} else {
43+
tr[i].style.display = "none";
44+
}
45+
}
46+
}
47+
}

0 commit comments

Comments
 (0)