I've made a table filled with data retreived from a JSON file. Now I'm trying to make a searchbar that filters searched items and only shows the table rows of the items searched for. The code of the function I'm using now is:
//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";
}
}
}
});
This is the HTML of the table I'm trying to apply the filter to:
<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>
Here is the best solution for searching inside HTML table while covering all of the table, (all td, tr in the table), pure javascript and as short as possible:
<body style="background:red;">
<input id='myInput' onkeyup='searchTable()' type='text'>
<table id='myTable'>
<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>
<tr>
<td>1</td>
<td>Green</td>
<td>Lorem</td>
<td>Ipsum</td>
<td>button</td>
</tr>
<tr>
<td>2</td>
<td>Green</td>
<td>elit</td>
<td>Mumbai</td>
<td>button</td>
</tr>
<tr>
<td>3</td>
<td>Green</td>
<td>sud</td>
<td>Dummy</td>
<td>button</td>
</tr>
</tbody>
</table>
<script>
function searchTable() {
var input, filter, found, table, tr, td, i, j;
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 (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";
}
}
}
</script>
</body>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With