I am new to JavaScript and looking to implement real-time filtering on a table based on user input. My project utilizes Django and PostgreSQL for storing the table data.
template
<form action="" method="get" class="inline">
<select name="column" class="form-control">
<option value="" selected disabled>Select field</option>
<option value="title">Title</option>
<option value="quantity">Quantity</option>
<option value="distance">Distance</option>
</select>
<label for="table">Condition</label>
<select name="condition" class="form-control">
<option value="" selected disabled>Select condition</option>
<option value="greater">Greater than</option>
<option value="contains">Contains</option>
<option value="lower">Lower than</option>
<option value="equals">Equals to</option>
</select>
<input class="form-control" type="text" placeholder="Search term" id="search-text" onkeyup="tableFilter()">
<button type="submit">Apply Filter</button>
</form>
https://i.sstatic.net/a0vMt.png
Thank you in advance for any assistance :)
Would this approach be effective?
function tableFilter() {
var input = document.getElementById("search-text");
var filter = input.value.toUpperCase();
var table = document.getElementById("myTable");
var tr = table.getElementsByTagName("tr");
for (var i = 0; i < tr.length; i++) {
var tds = tr[i].getElementsByTagName('td');
var firstCol = tds[0].textContent.toUpperCase();
var secondCol = tds[1].textContent.toUpperCase();
if (firstCol.indexOf(filter) > -1 || secondCol.indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}