I have created a webpage for a restaurant menu. At the top of the page there is a simple search input bar that users can use to type in a specific item name. The goal is that as soon as the user starts typing, the menu will filter results of the matching items, whilst hiding the rest. I do not want to use a button or anything for this to work; I would just like the filtering to occur as soon as the user starts typing. Here is my css to hide the menu cards (which include the name of the item, details and price) that are filtered out.
CSS:
.menu-card .hidden {
display: none;
}
And here is a snippet of the HTML (there are multiple menu-cards like the one below):
<div class="searchbar">
class="fa-solid fa-magnifying-glass">
<input type="search" id="search" placeholder="Search menu" data-controller="search-bar" data-action="input->search-bar#search">
</div>
<div class="menu-card" data-search-bar-target="menuCard">
<h4 class="item-name">Greek Village Salad with Feta</h4>
<p class="item-details">Tomato, cucumber, green pepper, red onion, feta in a rich salad</p>
<p class="item-price">£10.00</p>
</div>
I have also set up a stimulus controller and I can confirm that it is all connected so that is not the issue here. I think something might be missing from my code but I can't seem to figure out why it isn't working. If anyone has an idea, any help would be great!
search_bar_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["menuCard"];
connect() {
}
search(event) {
console.log(event);
const searchInput = event.target.value.toLowerCase();
this.menuCardTargets.forEach((menuCard) => {
const itemName = menuCard.querySelector(".item-name").textContent.toLowerCase();
if (itemName.includes(searchInput)) {
menuCard.classList.remove("hidden");
} else {
menuCard.classList.add("hidden");
}
});
}
}
What I have tried:
I have tried a couple of things to no avail! I even considered adding a button but I would rather not.