Currently, I have created a table populated with data fetched from a JSON file. Now, my focus is on implementing a search functionality that filters out items based on user input and displays only those table rows matching the search criteria. The code snippet for the function I am currently using is as follows:
// Search function
function searchTable() {
var input, filter, found, table, tr, td, i, j;
input = document.getElementsByClassName("searchBar");
filter = input.value.toUpperCase();
table = document.getElementById("productTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
}
}
if (found) {
tr[i].style.display = "";
found = false;
} else {
tr[i].style.display = "none";
}
}
}
Below is the HTML structure of the table where I intend to implement the search filter:
<input class="form-control searchBar" type="text" name="search" placeholder="search">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Product Name</th>
<th scope="col">Free Stock</th>
<th scope="col">Price</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody id="productTable">
<tr>
</tr>
</tbody>
</table>