This repository has been archived on 2020-08-02. You can view files and clone it, but cannot push or open issues or pull requests.
e-commerce/prototype/src/main/resources/static/js/filterTable.js

69 lines
1.7 KiB
JavaScript

function filterTable(caller) {
let target = caller.dataset.targetId;
let searchTerm = caller.value;
let table = document.getElementById(target);
let tds = Array.from(table.getElementsByTagName("tr")).filter(elm =>
elm.getElementsByTagName("th").length == 0
);
let matching = [];
let notMatching = [];
for (let td of tds) {
if (td.innerText.toLowerCase().includes(searchTerm.trim().toLowerCase())) {
matching.push(td);
} else {
notMatching.push(td);
}
}
let valid = matching.length > 0 || tds.length == 0;
if (valid) {
caller.setCustomValidity("");
for (let td of notMatching) {
td.style.display = "none";
}
for (let td of matching) {
td.style.display = null;
if(td.dataset.group) {
for(inner of notMatching) {
if(td.dataset.group == inner.dataset.group) {
inner.style.display = null;
}
}
}
}
} else {
caller.setCustomValidity("Nothing Matched");
for (let td of tds) {
td.style.display = null;
}
}
}
document.addEventListener("DOMContentLoaded", function(event) {
let elms = document.getElementsByClassName("jsFilterTable");
for (let elm of elms) {
elm.addEventListener('oninput', () => filterTable(elm));
elm.addEventListener('onpaste', () => filterTable(elm));
elm.addEventListener('keyup', () => filterTable(elm));
window.setTimeout(function() {
filterTable(elm);
}, 1);
}
for (let elm of elms) {
// get query value
let h = new URLSearchParams(window.location.hash.replace('#', '?', 1))
if (h.get('q')) {
elm.value = h.get('q');
}
}
});