Files
Projektwebshop/script.js
2025-12-03 12:40:07 +01:00

61 lines
2.3 KiB
JavaScript

document.addEventListener("DOMContentLoaded", () => {
const form = document.getElementById("filters");
const table = document.querySelector("table tbody");
const rows = Array.from(table.querySelectorAll("tr"));
form.addEventListener("submit", (e) => {
e.preventDefault();
const search = form.search.value.toLowerCase();
const category = form.category.value;
const minPrice = parseFloat(form.minPrice.value);
const maxPrice = parseFloat(form.maxPrice.value);
const sort = form.sort.value;
let filteredRows = rows.filter(row => {
const cells = row.querySelectorAll("td");
const name = cells[1].textContent.toLowerCase();
const cat = cells[3].textContent;
const price = parseFloat(cells[4].textContent);
let matchesSearch = !search || name.includes(search);
let matchesCategory = category === "all" || cat === category;
let matchesMinPrice = isNaN(minPrice) || price >= minPrice;
let matchesMaxPrice = isNaN(maxPrice) || price <= maxPrice;
return matchesSearch && matchesCategory && matchesMinPrice && matchesMaxPrice;
});
filteredRows.sort((a, b) => {
const aCells = a.querySelectorAll("td");
const bCells = b.querySelectorAll("td");
switch(sort) {
case "price-asc":
return parseFloat(aCells[4].textContent) - parseFloat(bCells[4].textContent);
case "price-desc":
return parseFloat(bCells[4].textContent) - parseFloat(aCells[4].textContent);
case "name-asc":
return aCells[1].textContent.localeCompare(bCells[1].textContent);
case "name-desc":
return bCells[1].textContent.localeCompare(aCells[1].textContent);
default:
return 0;
}
});
table.innerHTML = "";
if(filteredRows.length === 0) {
const tr = document.createElement("tr");
tr.innerHTML = `<td colspan="5" style="text-align:center;">Keine Produkte gefunden.</td>`;
table.appendChild(tr);
} else {
filteredRows.forEach(row => table.appendChild(row));
}
});
});