How to trigger search on enter key and button click javascript?

Viewed 30

I want to trigger the search button to work when the "search" button is clicked and when the enter key on the keyboard is pushed. So far, the search works when the button is clicked. How do I add that to this code?

Thanks!

//Search button click
document.getElementById("search").addEventListener("click", () => {
    //initializations 
    let searchInput = document.getElementById("search-input").value;
    let elements = document.querySelectorAll(".question-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.toString())){
            //display matching card
            cards[index].classList.remove("hide");
        }
        else {
            //hide others 
            cards[index].classList.add("hide");
        }

    })
});
1 Answers
Related