What is the best way to store checkbox statuses in local storage and display them again in a JavaScript to-do list?

I'm currently working on a to-do list application using basic JavaScript. One issue I'm facing is saving the checked status of the checkbox input element and displaying it again after the page is refreshed. Since I'm still learning JavaScript, I might need to change my approach to handling checkboxes. Can you suggest the best method to achieve this?

Below is the code snippet:

<!-- Your code goes here -->

In the code provided, I attempted to loop through the checkboxes to add a "checked" attribute to those with corresponding indices in the saved to-do list array. I also added an event listener to each element to track their checked status and update the check property in the to-do list object accordingly. However, upon page refresh, the check property reverts to false, and no checked attributes are rendered. Even though the array's check attribute updates to true when I log it after checking the checkbox, it resets back to false upon refreshing the page.

Answer №1

There are two key issues with the provided code:

  1. The first problem lies in how toDoListArray is initially set up in the code snippet. The expected structure should resemble this format:

    [
      {
        inputValue: "wash the dishes",
        dateValue: "1-1-2023",
        check: false,
      },
      {
        inputValue: "checked example 2",
        dateValue: "22-3-2025",
        check: true,
      },
    ]
    

    However, the initial assignment of toDoListArray using

    JSON.parse(localStorage.getItem("items"))
    creates a different structure as an object within an array.

    To rectify this issue, it is recommended to adjust the initialization of toDoListArray as follows:

    let toDoListArray = JSON.parse(localStorage.getItem("items")) || [
      {
        inputValue: "wash the dishes",
        dateValue: "1-1-2023",
        check: false,
      },
      {
        inputValue: "checked example 2",
        dateValue: "22-3-2025",
        check: true,
      },
    ];
    


  1. The second critical issue relates to the persistence of checkbox status upon page reloads. The checkboxes state needs to be updated and saved in the localStorage when their value changes.

    A solution for this problem involves updating the localStorage on checkbox state changes, like so:

    element.addEventListener("change", () => {
      if (element.checked) {
        toDoListArray[idx].check = true;
      } else {
        toDoListArray[idx].check = false;
      }
    
      localStorage.setItem("items", JSON.stringify(toDoListArray));
    });
    


Revised Final Code:

let toDoListArray = JSON.parse(localStorage.getItem("items")) || [{
    inputValue: "wash the dishes",
    dateValue: "1-1-2023",
    check: false,
  },
  {
    inputValue: "checked example 2",
    dateValue: "22-3-2025",
    check: true,
  },
];

// remaining code for handling user input, managing checkboxes, etc.
* {
  /* CSS styles */
}

/* Additional HTML code and styling for the application */

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>vanilla javascipt ToDoList</title>
</head>

<body>
  <main>
    <p class="header">To-Do-List</p>
    <div class="form">
      <input placeholder="type the task" type="text" class="task-input" />
      <input type="date" class="date-input" />
      <button class="add" onclick="addItem()">Add</button>
    </div>
    <div class="list"></div>
  </main>
</body>

</html>

Answer №2

It appears that the issue lies in not updating the localStorage when the checkbox is clicked.

element.addEventListener("change", () => {
      if (element.checked) {
        toDoListArray[idx].check = true;
      } else {
        toDoListArray[idx].check = false;
      }
    });

The event modifies the checked state but fails to trigger the localStorage.setItem function, which is specifically located in the addItemHTML section.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to display certain JSON elements

I'm attempting to retrieve a specific part of a JSON file through AJAX and display it in an HTML div. I only want to show a certain object, like the temperature. Here is the AJAX code: $(function () { $.ajax({ 'url': 'http://ap ...

Establishing a connection with MSSQL 2014 through Node.js

I've been grappling with this issue for quite some time and I just can't seem to figure it out. Here is the code snippet that I have been using: const sql = require('mssql/msnodesqlv8'); const pool = new sql.ConnectionPool({ server: ...

Table order is requested, but the index fails to comply

I am facing an issue with sorting and deleting data from a JSON table. Even after sorting the columns, clicking "Delete" removes the wrong entry because the $index is not updated properly. Here is the JavaScript code I am using: $scope.friends = ...

Encasing the bootstrap dropdown menu and trigger within individual parent divs for a tidier appearance

Is it possible to toggle a bootstrap dropdown when it is wrapped in another div by using attributes such as data-target or aria-labelledby? I have seen examples where data-toggle="dropdown" and class="dropdown-menu" are siblings. An example of what I am r ...

Loop through and write files using Node.js

I've been experimenting with a Google Trends API integration in node.js to gather data on the popularity of various search terms. My goal is to store a list of search words in an array, iterate through this array, call the Google Trends API for each ...

Concealing an input field in AngularJS

I am currently developing a login page with register and login options using AngularJS. The interface includes three input fields: username, password, and name. I aim to display the name field upon clicking the register button and hide it upon clicking t ...

Attempting to console.log data from within useEffect, but unfortunately no information is being logged

function FetchUserAccounts() { const [userAccounts, setUserAccounts] = useState(); useEffect(() => { async function fetchUserAccountsData() { const response = await fetch( 'https://proton.api.atomicassets.io/atomicassets/v1/a ...

conceal parent window element upon clicking an image within an iframe

I'm facing a challenge with hiding certain buttons in a parent window when opening a modal by clicking an image inside an iframe. Below is the code snippet that I am using: In the parent window - <iframe id="gallery" src="links/gallery.html" wid ...

The footer should always be anchored at the bottom of the webpage, maintaining a consistent position regardless of any changes to the browser's

I've successfully implemented a footer with several buttons that remains positioned at the bottom of the page, 60px above the very bottom, regardless of the content or window size. The CSS I'm using is as follows: #container { min-height: 10 ...

Upon running the command "React + $ npm start," an error occurred with the code 'ERR_OSSL_EVP_UNSUPPORTED' related to opensslErrorStack

When running $npm start, an error is being thrown: opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ], library: 'digital envelope routines', reason: 'unsupported', code: 'ERR_OSSL_EVP_ ...

Is there a way to apply border-radius to the header of a table in Bootstrap 5?

My use of Bootstrap 5 for styling a table has encountered an issue. Even with the border-radius set on the table-dark class, the thead element's border does not change. I am looking for a way to address this problem. Any suggestions? .table-dark { ...

A <div> with relative positioning is inhibiting the visibility of absolutely positioned elements without any visible overlap

Recently, I encountered a strange issue on my webpage: Image of page The lines on the left side are supposed to be displayed behind or on top of the text box. However, when I increase their z-index, the lines extend all the way to the top of the page and g ...

The wrapAll() method can be used to wrap list items within two columns

I am looking to group multiple li elements within two div containers by using jQuery's wrapAll method. The challenge lies in the fact that these items are rendered within a single <ul> element via a CMS. Here is the current setup: <ul> ...

NodeJS package 'jquery' npm not functioning properly (issue with $.on())

I've successfully installed and loaded jquery by using $ = require('jquery'); However, when I attempt to utilize it: app.get('/', function (req, res) { res.render('index'); $.on('ready', function () { ...

Is there a way to simultaneously view and send this JSON data to the server using console.log?

I'm looking to inspect the JSON data being sent and received by the server, but I'm struggling to understand how promises work in this scenario. When I use console.log() on the function body, I see Promise { pending }. Unfortunately, I can' ...

The key to successful filtering in Next.js with Hasura is timing - it's always a step

I am fetching data from Hasura using useRecipe_Filter and passing the searchFilter state as a variable. It seems that every time I press a key, the UI updates with one keystroke delay before filtered data is passed to the results state. const SearchBar = ( ...

Ways to delete a header from the req object in Express

Can anyone help me understand how to remove a header from the req object in Express? I've heard that using res.disable("Header Name") can do this for the res object, but it doesn't seem to work for req.headers. ...

When adding new elements to an array, the IDs of all objects become identical

When running the code below: dietDay.meals.forEach((meal) => { meal.mealProducts.forEach((mealProduct) => { if ( mealProduct.product.id && this.fetchedProductIds.includes(mealProduct.p ...

An error was encountered while linting /app/layout.tsx at line 16: Rule "@typescript-eslint/no-empty-function" was violated due to inability to read properties of undefined (reading 'getTokens')

I am puzzled as to why the function that generates JSX is being checked by the "next lint" script with the rule "@typescript-eslint/no-empty-function". The code snippet at line 16 of the layout.tsx file looks like this: export default function RootLayout( ...

Compiling Nextjs with Tailwind typically takes anywhere from 8 to 16 seconds

My first time using tailwind has resulted in slow compilation times when used with nextjs in development mode. The slowdown can be confirmed by simply removing the following code: @tailwind base; @tailwind components; @tailwind utilities; This significan ...