skip to Main Content

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


  1. Basically you should create a function which will be called when you press enter and attach it to the event of the element.

    function actionOnEnter(e: event) {
     const key = e.keyCode || e.which;
    
     if(key == 13) {
      doSomething()
     }
    }
    

    If you don’t know what event to use, check this out: onKeyPress Vs. onKeyUp and onKeyDown.

    Login or Signup to reply.
  2. Key Enter detection JS:

    document.addEventListener("keydown", 
    function(event) {
    (key code 13)
    if (event.key === "Enter") {
      //Code
    }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search