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 in my code 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() {
// console.log("Hello, you are inside the search_bar controller!");
}
search(event) {
console.log(event);
const searchInput = event.target.value.toLowerCase(); // assigns the value of the text in the input field
this.menuCardTargets.forEach((menuCard) => {
const itemName = menuCard.querySelector(".item-name").textContent.toLowerCase();
if (itemName.includes(searchInput)) { // if the name of the menu item is the same as whatever is inputted in the search field
menuCard.classList.remove("hidden"); // display the menu card of the menu item
} else {
menuCard.classList.add("hidden"); // hide the menu card of all the items that do not match the input
}
});
}
}