I am currently working on a task management application where users can input items into a list. The entered item is displayed on the page and also added to an array named "items".
While adding and removing items from the page works smoothly, I'm facing challenges with removing items from the array itself. It seems that synchronizing the removal of items from both the page and the array is not as straightforward as I expected.
The array will be utilized for another purpose, so it's crucial to keep it updated. I have experimented with using the splice method to remove items from the array but encountered some issues in implementation.
I even tried revising my approach by first adding items to the array and then dynamically displaying them on the page using a for loop. However, this didn't resolve the problem either.
If anyone can offer guidance or assistance, I would greatly appreciate it! You can access the live version of the app through the following link hosted on my Neocities account:
Below is a snippet of the code I am currently working on:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#myList {
list-style: none;
}
li {
padding: 10px;
max-width: 300px;
background-color: rgb(186, 255, 129);
font-size: larger;
font-weight: bold;
border-style: double;
border-radius: 10px;
text-align: center;
margin: 5px;
}
.remove-btn {
float: right;
background-color: red;
color:black;
}
#itemAdd {
padding: 10px;
font-size: larger;
text-align: center;
}
#itemName {
padding: 10px;
max-width: 300px;
font-size: larger;
font-weight: bold;
border-style: double;
text-align: center;
}
</style>
</head>
<body>
<div class="container main">
<form action="" method="post">
<input type="text" id="itemName">
<button onclick="addItem()" id="itemAdd">ADD</button>
</form>
<div>
<ul id="myList">
</ul>
</div>
</div>
<script>
let items = [];
const addItem = () => {
event.preventDefault();
let myList = document.getElementById('myList');
let listItem = document.createElement('li');
listItem.innerText = itemName.value + " ";
myList.append(listItem);
let removeButton = document.createElement('button');
removeButton.innerText = "-";
removeButton.className = "remove-btn"
removeButton.addEventListener('click', removeItem);
listItem.append(removeButton);
items.push(itemName.value);
document.forms[0].reset();
}
const removeItem = () => {
let item = event.currentTarget.parentNode;
item.remove();
let itemIndex = items.indexOf(item);
items.splice(itemIndex, 1);
}
</script>
</body>
</html>