Start learning free

LESSON 38 OF 161 · FRONTEND: JAVASCRIPT IN THE BROWSER

Filter While Typing

Practice

An input event fires on a text box every time its value changes: each letter typed, each letter deleted. Listen to it and the page can react while the visitor types, with no button to press.

const city = document.querySelector("#city");
city.addEventListener("input", () => {
  console.log("You typed: " + city.value);
});

To keep only some items of an array, use filter; to look for a piece of text anywhere in a string, use includes. For example, ["Oslo", "Lisbon", "Paris"].filter((c) => c.toLowerCase().includes("is")) gives ["Lisbon", "Paris"]. includes cares about capitals, so lower-case both the name and what was typed. And "Oslo".includes("") is true: an empty box matches everything.

Show the result the same way you drew the cart: rebuild the list from the matching data with replaceChildren. classList.toggle("hidden", force) adds the class when force is true and removes it when it is false.

The check types "Pl", then "z", then presses Backspace three times. The products section must show:

> type "Pl" into "Search"   text: 2 products   Plant, Stapler
> type "z" into "Search"    text: 0 products   list (empty)   text: No products match
> press Backspace           text: 2 products   Plant, Stapler
> press Backspace           text: 5 products   Lamp, Pen, Plant, Teapot, Stapler
> press Backspace           text: 8 products   all eight again

Your task: listen to the input event of #search. At each change, keep the products whose lower-case name includes the lower-case text, rebuild #products from them with productCard, write the count, and show #no-match only when nothing matches.


Assignment
Follow the Coding Tutorial to filter the product list as the visitor types in the Search box.


Hint
Filter PRODUCTS every time, not the cards on the page, so deleting a letter brings products back. The message should be hidden when there is at least one match: matches.length > 0.


STEP 1 OF 8
    Ctrl + Enter to check