Advertisement
EntropyStarRover

05. Fill dropdown

Mar 12th, 2021
653
0
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 addItem() {
  3.     let menu = document.getElementById("menu");
  4.  
  5.     function optionTemplate(o) {
  6.         return html`<option value=${o._id}>${o.text}</option>`
  7.     }
  8.  
  9.     function renderOptions(arr) {
  10.         let options = arr.map(o => optionTemplate(o));
  11.         render(options, menu)
  12.     }
  13.  
  14.     //    load existing
  15.  
  16.     function loadExisting() {
  17.         let requestOptions = {
  18.             method: 'GET',
  19.             redirect: 'follow'
  20.         };
  21.  
  22.         fetch("http://localhost:3030/jsonstore/advanced/dropdown", requestOptions)
  23.             .then(response => response.json())
  24.             .then(result => renderOptions(Object.values(result)))
  25.             .catch(error => console.log('error', error));
  26.     }
  27.  
  28.     loadExisting();
  29.  
  30.  
  31.     let form = document.querySelector("form");
  32.     form.addEventListener("submit", function (e) {
  33.         e.preventDefault();
  34.         let itemName = document.getElementById("itemText").value;
  35.         submitItem(itemName);
  36.     })
  37.  
  38.     function submitItem(itemName) {
  39.         let body = { text: itemName }
  40.  
  41.         let myHeaders = new Headers();
  42.         myHeaders.append("Content-Type", "application/json");
  43.  
  44.         let raw = JSON.stringify(body);
  45.  
  46.         let requestOptions = {
  47.             method: 'POST',
  48.             headers: myHeaders,
  49.             body: raw,
  50.             redirect: 'follow'
  51.         };
  52.  
  53.         fetch("http://localhost:3030/jsonstore/advanced/dropdown", requestOptions)
  54.             .then(response => response.json())
  55.             .then(result => loadExisting())
  56.             .catch(error => console.log('error', error));
  57.  
  58.         document.getElementById("itemText").value = "";
  59.     }
  60. }
  61.  
  62. addItem();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement