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>
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>