Reputation: 21
I'm having trouble deleting a specific item in the localStorage array in my Javascript to-do list app.
Upon entering the input value, the value is pushed to the myList array and to local storage using localStorage.setItem("myList", JSON.stringify(myList)).
Users can delete an item from the screen by clicking on the delete button next to it, but when the page is refreshed, the item keeps appearing. This is because the item in the local storage is not deleted.
When the user clicks on the delete button next to that item, how do I delete it from the local storage array?
let myList = []
const submitBtn = document.getElementById("submit-btn");
const clearListBtn = document.getElementById("clearList-btn");
const inputEl = document.getElementById("input-btn");
const olEl = document.getElementById("ol-el");
const doneBtn = document.getElementById("done-btn");
const leadFromLocalStorage = JSON.parse(localStorage.getItem("myList"))
if (leadFromLocalStorage) {
myList = leadFromLocalStorage;
render(myList);
}
function render(leads) {
let listItems = " ";
for ( let i = 0; i < leads.length; i++) {
listItems +=
`<li id = " ">
${leads[i]} <button id= "done-btn" onclick = "deleteButton(${i})">X</button>
</li>
`;
}
olEl.innerHTML = listItems;
}
submitBtn.addEventListener("click", function() {
myList.push(inputEl.value);
inputEl.value = " ";
localStorage.setItem("myList", JSON.stringify(myList))
render(myList);
})
clearListBtn.addEventListener("click", function() {
localStorage.clear();
myList = [];
render(myList)
})
function deleteButton(index) {
myList.splice(index, 1);
render(myList);
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="box">
<p>To-Do List</p>
<input value = "Add an item!" id = "input-btn">
<button id = "submit-btn">submit</button>
<button id = "clearList-btn">clear list</button>
<ol id="ol-el"></ol>
<script src = "index.js"></script>
</div>
</body>
</html>
Upvotes: 0
Views: 36
Reputation: 348
In your deleteButton
function, you can add a line after where you splice the array to sync your list with the one in the localStorage
.
localStorage.setItem("myList", JSON.stringify(myList));
Upvotes: 0