Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

395
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda