I have a function that is attached to two different search inputs. In my for loop i loop through the rows and either filter the first or third column based on which search input was used. Having two if statements in the loop doesn't feel right, how can i refactor this?
// attach keyup event listener to input
document.getElementById("search-rule").addEventListener("keyup", searchVehicle);
document.getElementById("search-region").addEventListener("keyup", searchVehicle);
var ruleEl = document.getElementById("search-rule");
function searchVehicle(event) {
// convert input to uppercase
var filter = event.target.value.toUpperCase();
// select rows in tbody
var rows = document.querySelector("#myTable tbody").rows;
// loop through the rows
// if the input searches by rule, search the first column
// else search the 3rd column (region)
// if in input show the row, if not in input, hide row
for (var i = 0; i < rows.length; i++) {
if (event.target === ruleEl) {
var colRule = rows[i].cells[0].textContent.toUpperCase();
} else {
var colRule = rows[i].cells[2].textContent.toUpperCase();
}
if (colRule.indexOf(filter) > -1) {
rows[i].style.display = "";
} else {
rows[i].style.display = "none";
}
}
}
You can use a ternary statement to set the display property:
I would also declare the
colRule
var at the top of the function and only assign it in the loop, rather than redeclare it.