I'm trying to make a to-do list. I'm in the middle of a process and get the following problem:
HTML:
<body>
<ul id="list">
</ul>
<form action="submit" id="task-form">
<input type="text" placeholder="Type your task here and click 'Add a Task'" id="task-input">
<button type="submit" id="add-button" > Add a Task </button>
</form>
<template id="template">
<li class="list-item" data-todo-id="">
<label class="list-item-label">
<input type="checkbox" id="checkbox">
<span list-item-text> Task text is here </span>
</label>
<button type="button"> Delete </button>
</li>
</template>
</body>
JS:
let button = document.querySelector('#add-button')
let todoInput = document.querySelector('#task-input')
let template = document.querySelector('#template')
let list = document.querySelector('#list')
let LOCAL_STORAGE_PREFIX = 'TO-DO LIST APP'
let LOCAL_STORAGE_KEY = `${LOCAL_STORAGE_PREFIX}-todos`
let todos = [];
let savedTodos = loadTodo();
savedTodos.forEach(renderTodo)
button.addEventListener('click', e =>{
e.preventDefault();
let date = new Date;
let todo = {
name : todoInput.value,
complete : false,
id : date.valueOf() }
todos.push(todo)
saveTodo();
renderTodo(todo)
console.log(todo)
todoInput.value = ''
})
function renderTodo(todoName){
let templateClone = template.content.cloneNode(true)
let todoText = templateClone.querySelector('[list-item-text]')
todoText.innerText = todoName.name
list.appendChild(templateClone)
}
function saveTodo(){
localStorage.setItem(LOCAL_STORAGE_KEY,JSON.stringify(todos))
}
function loadTodo(){
return JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) || []
}
The checkbox doesn't have any event handlers attached, so checking/unchecking it will have no effect on the todos. However, you have a bug in your code, which will lead to all your previously saved todos being deleted if you add a new one. The checkbox thing, I believe was a co-incidence.
let todos = [];
let savedTodos = loadTodo();
Here two different arrays are being created, savedTodos contains the todo lists parsed from local storage. And an empty array called todos. The list of todos in savedTodos also gets added to dom on next line.
So far so good..
...
todos.push(todo)
saveTodo();
renderTodo(todo)
...
However, in your addTodo function (add button event handler), when you add a new todo it is added to the (currently empty) todos array, and then is also written back to the local-storage. At this point, the existing todos will show in DOM, but have been deleted from local-storage. When you refresh the page, only the Todos added in the last session will show.
To fix this, I's recommend merging the todos and savedTodos array, and having only one of those.
...
let allTodos = loadTodo();
allTodos.forEach(renderTodo)
// in addTodo function (add button event handler)
...
allTodos.push(todo);
...
// in saveTodo function
localStorage.setItem(LOCAL_STORAGE_KEY,JSON.stringify(allTodos));