Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

393
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!