I am trying to make a simple grocery list program. There is an add item and a remove item button. There is also a textbox. For example, when you type ‘apples’ into the text field and hit the add button. The add button should then put ‘apples’ in groceryList Array and then display apples in the div area labeled groceryinfo.
The remove button also won’t work. For example, if you have five different items in the list if the value entered into the text field is ‘apples’. Apples should be found and then removed. The groceryList array should then redisplay and show the array contains without the deleted item.
<body>
My grocery list
<br>
<br>
<div id="groceryinfo"></div>
<br>
<br>
<input id="Button1" type="button" value="Add this item" onclick="Add()" /><input id="Text1" type="text" />
<br>
<input id="Button2" type="button" value="Remove this item" onclick="Remove()" />
<script>
var groceryList = [];
var groceryitem;
var description;
description = document.getElementById("groceryinfo");
function Add() {
groceryitem = document.getElementById('Text1').value;
groceryList.push(groceryitem);
groceryList = description;
}
function Remove() {
for (var i = 0; i <= groceryList.length; i ) {
if (groceryList[i] == groceryitem) groceryList.splice(i, 1);
groceryList = description;
}
}
</script>
CodePudding user response:
You can achieve this with document.getElementById("groceryinfo").innerHTML
like so:
<body>
My grocery list
<br>
<br>
<div id="groceryinfo"></div>
<br>
<br>
<input id="Button1" type="button" value="Add this item" onclick="Add()" /><input id="Text1" type="text" />
<br>
<input id="Button2" type="button" value="Remove this item" onclick="Remove()" />
<script>
var groceryList = [];
var groceryitem;
var description;
description = document.getElementById("groceryinfo");
function Add() {
groceryitem = document.getElementById('Text1').value;
groceryList.push(groceryitem);
document.getElementById("groceryinfo").innerHTML = groceryList.toString();
}
function Remove() {
for (var i = 0; i <= groceryList.length; i ) {
if (groceryList[i] === groceryitem) {
groceryList.splice(i, 1);
document.getElementById("groceryinfo").innerHTML = groceryList.toString();
}
}
}
</script>