Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

102
Vistas
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:

  1. I render a todo from input to a page - works fine.
  2. I save todos in local storage - works fine.
  3. 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)) || [] 
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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));
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda