Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

398
Visualizações
Using JavaScript to add input text to an li, but only adding certain words

Right now I'm working on a menu project where customers input text, and it sends what they wrote into a separate ul in a separate div, sort of like a shopping cart menu.

Everything works fine, but I realized I can type anything I want into this div, including gibberish, and it will show up. I'd like to make an array of allowed words (ex: Pasta, Milk, Eggs, etc.), but I'm struggling to think of a way to write that. I was thinking of using an if statement but not sure exactly how I'd write it. Any help would be appreciated.

function addLi() {
  let input    = document.getElementById("input").value;
  let listNode = document.getElementById("list");
  let liNode   = document.createElement("li");
  let txtNode  = document.createTextNode(input);
  liNode.appendChild(txtNode);
  listNode.appendChild(liNode);
}
<div class="menu-items">
  <h2>Added Items</h2>
  <ul id="list">

  </ul>
</div>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Create an array of allowed terms, and inside your function check whether the value entered is in that list:

const whiteList = ['pasta', 'milk', 'apples'];

function addLi() {
  let input = document.getElementById("input").value;
  if (whiteList.includes(input.toLowerCase())) {
    const listNode = document.getElementById("list");
    const liNode = document.createElement("li");
    const txtNode = document.createTextNode(input);
    liNode.appendChild(txtNode);
    listNode.appendChild(liNode);
  }
}

document.getElementById('addItem').addEventListener('click', addLi);
<div class="menu-items">
  <h2>Added Items</h2>
  <input type="text" id="input"> <button type="button" id="addItem">Add Item</button>
  <ul id="list"></ul>
</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda