Advertisement
EntropyStarRover

05. Table Search- Engine

Mar 12th, 2021
626
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { html, render } from 'https://unpkg.com/lit-html?module';
  2. function solve() {
  3.    let cached=[];
  4.    document.querySelector('#searchBtn').addEventListener('click', onClick);
  5.    let inputField = document.getElementById("searchField")
  6.  
  7.    let tbody = document.querySelector("tbody");
  8.    console.log(tbody)
  9.  
  10.    //get data
  11.    let myHeaders = new Headers();
  12.    myHeaders.append("Content-Type", "application/json");
  13.  
  14.    let requestOptions = {
  15.       method: 'GET',
  16.       headers: myHeaders,
  17.       redirect: 'follow'
  18.    };
  19.  
  20.    fetch("http://localhost:3030/jsonstore/advanced/table", requestOptions)
  21.       .then(response => response.json())
  22.       .then(result => populateTable(Object.values(result)))
  23.       .catch(error => console.log('error', error));
  24.  
  25.    function rowTemplate(r) {
  26.       return html`
  27.    <tr>
  28.                 <td>${r.firstName} ${r.lastName}</td>
  29.                 <td>${r.email}</td>
  30.                 <td>${r.course}</td>
  31.             </tr>`
  32.    }
  33.  
  34.    function selectedRowTemplate(r) {
  35.       return html`
  36.       <tr class="select">
  37.       <td>${r.firstName} ${r.lastName}</td>
  38.       <td>${r.email}</td>
  39.       <td>${r.course}</td>
  40.   </tr>`
  41.    }
  42.  
  43.    function populateTable(data) {
  44.       let rows = data.map(d => rowTemplate(d));
  45.       cached=data;
  46.       render(rows, tbody);
  47.    }
  48.  
  49.    function onClick() {
  50.       let queryString = inputField.value;
  51.  
  52.       let differentLis = [];
  53.       cached.forEach(r => {
  54.          let rowTextContentArr=[r.firstName, r.lastName, r.email,r.course]
  55.          let rowTextContent=rowTextContentArr.join(" ")
  56.          if (rowTextContent.toLowerCase().includes(queryString.toLowerCase())) {
  57.          
  58.             differentLis.push(selectedRowTemplate(r))
  59.          } else {
  60.             differentLis.push(rowTemplate(r))
  61.          }
  62.       })
  63.  
  64.       inputField.value="";
  65.       render(differentLis, tbody);    
  66.    
  67.    }
  68. }
  69.  
  70. solve();
Advertisement
RAW Paste Data Copied
Advertisement