I need help with this assignment. the directions are: modify the JavaScript so t
ID: 3904968 • Letter: I
Question
I need help with this assignment. the directions are:
modify the JavaScript so that it does not allow the user to enter something that is already on the list. If an item is already there, the code should pop up a message saying that it is already on the list and not allow a duplicate to be added. You will need to understand how to work with arrays and for-loops for this one and how to search an array to find out what is there. You can modify my answer for shoppingList.js if you want to but note that I attached a space to the item name before I put it in the text node so you will have to trim the contents of the text.
SHOPPINGLIST.HTML
SHOPPINGLIST.JS
<!DOCTYPE html> <html> <head> <title>Shopping List</title> <script src="shoppinglist.js" language="javascript"></script> <style> body{ margin: 0 auto; width: 80%; } header, #inputArea, #outputArea, footer, #buttonArea{ padding: 1em; color: white; background-color: #DAA835; text-align: center; border: 1px dashed black; margin-bottom: 10px; } #inputArea, #buttonArea{ text-align: left; width: 30%; float: left; } #buttonArea{ margin-left: 1%; text-align: center; } #outputArea{ text-align: left; width: 30%; float: right; padding-top: 0; } #outputArea h3{ margin-top: 0; } label, input{ display: inline-block; } input{ width: 200px; } footer{ clear: both; } </style> </head> <body> <header> <h1>Shopping List App</h1> </header> <div id="inputArea"> <label>Enter list item:</label> <input type = "text" id = "listItem"> </div> <div id="buttonArea"> <button id = "calcBtn" >Click to add item to the list</button> </div> <div id="outputArea"> <h3>Shopping List</h3> <ul id="listArea"> </ul> </div> <footer> Created by: DGB ©2018 </footer> </body>Explanation / Answer
if you have any doubts, please give me comment...
function addItemToList(button) {
var input = document.getElementById("listItem");
if (input.value.trim().length == 0) {
alert("There must be an item entered");
return;
}
var listArea = document.getElementById("listArea");
var listEls = listArea.children;
for(var i=0; i<listEls.length; i++){
if(listEls[i].innerText=="X"+input.value.trim()){
alert("Already existed");
return;
}
}
var itemEl = document.createElement("li");
var buttonEl = document.createElement("button");
buttonEl.innerHTML = "X";
buttonEl.addEventListener("click", function () {
if (confirm("Would you like to delete the selected item?")) {
var parentEl = this.parentElement;
var listArea = document.getElementById("listArea");
listArea.removeChild(parentEl);
}
});
itemEl.appendChild(buttonEl);
var textNode = document.createTextNode(input.value.trim());
itemEl.appendChild(textNode);
listArea.appendChild(itemEl);
}