Advertisement
EntropyStarRover

03. Search in list

Mar 12th, 2021 (edited)
505
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { towns } from "./towns.js";
  2. import { html, render } from 'https://unpkg.com/lit-html?module';
  3.  
  4. function search() {
  5.    let button = document.querySelector("button")
  6.    let input = document.getElementById("searchText");
  7.  
  8.  
  9.    let townsDiv = document.getElementById("towns");
  10.    function createTownTemplate(town) {
  11.       return html`      
  12.       <li>${town}</li>`
  13.    }
  14.  
  15.    let townsLis = towns.map(t => createTownTemplate(t));
  16.    let ul = document.createElement("ul");
  17.    render(townsLis, ul);
  18.    render(ul, townsDiv)
  19.  
  20.  
  21.    button.addEventListener("click", function (e) {
  22.       let matches = 0;
  23.       let searchQuery = input.value;
  24.  
  25.       function createActiveLi(town) {
  26.          return html`
  27.              <li class="active">${town}</li>`
  28.       }
  29.  
  30.       let differentLis = [];
  31.       towns.forEach(t => {
  32.          if (t.toLowerCase().includes(searchQuery.toLowerCase())) {
  33.             matches++;
  34.              differentLis.push(createActiveLi(t))
  35.          } else {
  36.             differentLis.push(createTownTemplate(t))
  37.          }
  38.       })
  39.  
  40.       render(differentLis, ul);
  41.       render(ul, townsDiv);
  42.       let resultDiv = document.getElementById("result");
  43.       resultDiv.textContent = `${matches} matches found`;
  44.    })
  45. }
  46.  
  47. search()
Advertisement
RAW Paste Data Copied
Advertisement