I've successfully created a todo list using Vanilla Javascript along with local storage. The todo list includes the following key-value pairs:
key: todolist
value: [[\"id:0\",\"title:buy groceries\",\"done:false\"],
[\"id:1\",\"title:pick up dry cleaning\",\"done:false\"],
[\"id:2\",\"title:walk dog\",\"done:false\"]]
Everything works perfectly on my website, displaying only the titles as intended. However, upon refreshing the page, the entire object is displayed instead.
Pre-refresh:
Post-refresh:
After a refresh, I wish for only the titles to be displayed within the li tags. This issue only arises after refreshing the page.
How can I ensure that only the titles display post-refresh?
I'm fairly new to Javascript and struggling to find a solution. After two days of searching through Google, I'm at my wits' end!
// establish variables for elements on the page
const form = document.querySelector('form');
const ul = document.querySelector('ul');
const button = document.querySelector('button');
const input = document.getElementById('item');
// address empty array when script runs by checking if localStorage exists
let itemsArray;
if (localStorage.getItem('todolist')) {
itemsArray = JSON.parse(localStorage.getItem('todolist'));
} else {
itemsArray = [];
}
localStorage.setItem('todolist', JSON.stringify(itemsArray));
const data = JSON.parse(localStorage.getItem('todolist'));
// function that creates an li element, sets the text, and appends it to the ul
const liMaker = (text) => {
const li = document.createElement('li');
li.textContent = text;
ul.appendChild(li);
// create a "close" button and append it to each list item
var span = document.createElement("SPAN");
var txt = document.createTextNode("🗑️");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
// define event listener to submit the input value
form.addEventListener('submit', function(e) {
e.preventDefault();
var id = "id:" + itemsArray.length;
var title = "title:" + input.value;
var done = "done:" + "false";
itemsArray.push([id, title, done]);
localStorage.setItem('todolist', JSON.stringify(itemsArray));
liMaker(input.value);
input.value = "";
});
data.forEach(item => {
liMaker(item);
});
// clear items from todolist
button.addEventListener('click', function () {
localStorage.removeItem("todolist");
while (ul.firstChild) {
ul.removeChild(ul.firstChild);
}
itemsArray = [];
});
One thing worth noting is that the page refresh issue doesn't occur when I change the following line of code:
itemsArray.push([id, title, done]);
to the following:
itemsArray.push(input.value);