Struggling with creating a task list with javascript and local storage?

How can I implement functionality in my HTML and JS files to save, read, and load values from local storage? Additionally, how can I automatically populate a list with these saved values and add a clear button for clearing the local storage?

let addToDoButton = document.getElementById('addToDo');
let toDoContainer = document.getElementById('toDoContainer');
let inputField = document.getElementById('inputField');


addToDoButton.addEventListener('click', function(){
    var paragraph = document.createElement('p');
    paragraph.classList.add('paragraph-styling');
    paragraph.innerText = inputField.value;
    toDoContainer.appendChild(paragraph);
    inputField.value = "";
    paragraph.addEventListener('click', function(){
        paragraph.style.textDecoration = "line-through";
        paragraph.style.color = "red";
    })
    paragraph.addEventListener('dblclick', function(){
        toDoContainer.removeChild(paragraph);
    })
})
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>To Do List</title>
</head>

<body>
  <label><h1>To Do List</h1></label>
    <div class="container">
      <input id="inputField" type="text" name="todo" id="todo">
      <button id="addToDo">+</button>

      <div class="to-dos" id="toDoContainer">
      </div>
    </div>
  <script src="main.js"></scr
ipt>

</body>

</html>

Answer №1

Give this a try

The snippet doesn't seem to be functioning correctly. You can view a working example here

let listContainer = document.getElementById('listContainer');
let textField    = document.getElementById('textField');
let items         = JSON.parse(localStorage.getItem('items') ?? '[]');

function addItems(){
    listContainer.innerHTML = items.map((item, index) => {
        return `<p class="${item.done ? 'done' : ''}" data-index="${index}">
                    ${item.name}
                    <button>x</button>
                </p>`
    }).join('');
}
document.getElementById('add-item-form').addEventListener('submit', event => {
    event.preventDefault();
    let name = textField.value.trim();

    if( name ){
        items.push({ name: name, done: false });
        textField.value = "";
        localStorage.setItem('items', JSON.stringify(items));
        addItems();
    }
});
listContainer.addEventListener('click', event => {
    if( event.target.tagName === 'P' ){
        let index = event.target.dataset.index;
        items[index].done = !items[index].done;
    }else if( event.target.tagName === 'BUTTON' ){
        let index = event.target.parentElement.dataset.index;
        items.splice(index, 1);
    }

    localStorage.setItem('items', JSON.stringify(items));
    addItems();
})

// load saved items
addItems();
.done {
    color: red;
    text-decoration: line-through;
}
<div class="container">
    <form id="add-item-form" autocomplete="off">
        <input type="text" id="textField">
        <button type="submit">+</button>
    </form>

    <div class="items-list" id="listContainer"></div>
</div>

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

How can I extract and print only the desired div content and send it via email from an HTML/JS page?

Is there a way to print only specific content within a div, rather than the entire webpage in JS/HTML? Below is the code snippet I am using: function displayRadioValue() { let section1 = document.querySelectorAll('.section-1 > input[type="ra ...

The content is not able to be shown within a frame due to the 'X-Frame-Options' being set to DENY during the Facebook fb.ui share method

Encountering this message in the console: Refused to display in a frame due to 'X-Frame-Options' set to DENY This issue arises when the website is displayed in its mobile version, which involves a distinct set of HTML and assets provided if the ...

Confirming User Authentication for Specific Path in MEAN Stack: A Step-by-Step Guide

Currently, I am in the process of learning the MEAN stack. Specifically, I have been working on setting up authentication using various packages such as passport-local, express-session, and passport-mongoose. I am not entirely sure if this is the best appr ...

What is the best way to transfer data from a PHP array to a jQuery array?

I can't seem to grasp the concept of transferring a PHP array to a jQuery array. I am trying to achieve something similar to this: var jQueryArray = <?php $phpArray; ?>; Could someone please provide guidance on how I can accomplish this? ...

Is there a more efficient alternative to the sluggish scroll event?

Currently, I have set up a scroll event that tracks the user's position on the page and updates the navigation styling based on which section they are viewing. However, the calculation I'm using during scrolling is quite resource-intensive and ca ...

Is there a way to fetch database content using ajax prior to triggering a filter keyup event?

I have encountered a challenge with my code below. It currently works when a filter parameter is pressed on keyup. However, I am looking to have the content of the database load via ajax as soon as the page is ready, even without any filter search being in ...

Include the JS file after finishing the control processing

I've been grappling with an issue for several days now. The view I have is populated by my controller through an API call, which works perfectly fine in rendering the HTML. $http.get(url). success(function(data, status, headers, config) { ...

The backend post request is returning only "undefined" in JavaScript

Hey there, I'm still learning JS so please bear with me. I've been working on incrementing a value in a JSON file within my JS backend app. However, whenever I try to increase the associated value by the key, it ends up creating a new section la ...

The sonar scanner encountered an error while attempting to parse a file using the espree parser in module mode

While executing sonar-scanner on a node project, I encounter a Failed to parse file issue, as shown below: ERROR: Failed to parse file [file:///home/node-app/somedir/index.js] at line 1: Unexpected token './AddCat' (with espree parser in mod ...

What is the best way to implement jQuery on an HTML file instead of relying solely on the Document Object Model

My attempt to make modifications to an HTML document has been challenging, as it differs from working with the DOM. I've realized that the syntax I typically use with the DOM doesn't translate well to this other document. For instance, while I co ...

Animate CSS during page load

Currently, I am implementing AJAX to dynamically load pages on my website. During the loading process, I wish to incorporate a spinning animation on the logo to indicate that content is being fetched. The jQuery script (although I'm still learning an ...

Guide on utilizing substring string functions in the updated version of Selenium IDE

I am facing a challenge with extracting the word "Automation" from a given string "Welcome to the Automation World" using Selenium IDE Record and Play feature. I have tried using the execute script command, but it doesn't seem to be working as expecte ...

Vue application encountering issues with the functionality of the split method in Javascript

Hey there! I am just starting out with JS and Vue. Currently, I have a Vue application that pulls date information from an open API. The tricky part is that the API response includes both the date and time in one string (for example: 2019-10-15T09:17:11.80 ...

The Angular integration with Semantic UI dropdown does not display the selected value clearly

I have put together a small example to demonstrate the issue. http://plnkr.co/edit/py9T0g2aGhTXFnjvlCLF Essentially, the HTML structure is as follows: <div data-ng-app="app" data-ng-controller="main"> <select class="ui dropdown" id="ddlStat ...

HighCharts: visualize vertical stacked bars displaying the distribution of percentages within each stack

I currently have a stacked bar chart similar to the one shown in this JSFiddle demo. My goal is to transform the stacks so that each bar represents a percentage of the total stack height. For instance, in the Apples stack we currently have values {3, 2, 5 ...

Leveraging the power of Redis client within an Express router

I would like to incorporate the use of a redis client in specific endpoints of my application. Here is how my app.js file is currently structured: //app.js const redis = require('redis'); const client = redis.createClient(process.env.REDIS_POR ...

Require receiving the feedback and implementing a modification in the ajax jquery graphical user interface

Currently, I am making a RESTful webservice call using jQuery AJAX and receiving the response in JSON format. Here is the jQuery HTML code: $.ajax({ url: "mcrs/object/api/Lighting", type: "POST", traditional: true, dataType: "json", ...

The Jquery AJAX call is sending the data twice

Why is my AJAX request uploading my form data twice into the database? Here's the code for the AJAX function: function uploadProjects() { let projectName = $('#projectName').val(); let description = $('#description').val(); ...

Getting the height of a div in a Nuxt.js application results in an error alert being displayed

Trying to retrieve the height of a div within a grid in a Nuxt application. <template> <div class="grid grid-cols-3"> <client-only> <Item v-for="( item, itemIndex ) in ItemsArray" ...

Ways to restrict the content div JSON display to only three items

Is it possible to limit the display of items from JSON in the content div to just three? The current code displays all downloaded items, but I want only 3 divs to be returned. <div id="p"></div> $.getJSON('element.json', function(d ...