'Why local storage deletes data with toggled checkboxes?
I'm trying to make a to-do list. I'm in the middle of a process and get the following problem:
- I render a todo from input to a page - works fine.
- I save todos in local storage - works fine.
- I load todos from local storage - works fine, BUT when I tick a checkbox on a todo and refresh the page local storage deletes that particular todo. Can't figure out what's going on
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)) || []
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
