In this exercise of searching for products with JavaScript, I need to incorporate a function where when I type the name of a product and press the "Enter" key it shows me the element.
document.getElementById("search").addEventListener("click", () => {
//initializations
let searchInput = document.getElementById("search-input").value;
let elements = document.querySelectorAll(".product-name");
let cards = document.querySelectorAll(".card");
//loop through all elements
elements.forEach((element, index) => {
//check if text includes the search value
if (element.innerText.includes(searchInput.toUpperCase())) {
//display matching card
cards[index].classList.remove("hide");
} else {
//hide others
cards[index].classList.add("hide");
}
});
});
2
Answers
Basically you should create a function which will be called when you press enter and attach it to the event of the element.
If you don’t know what event to use, check this out: onKeyPress Vs. onKeyUp and onKeyDown.
Key Enter detection JS: