Storing data locally for a task management application

This is a standard to-do list. You can add or remove items, but the problem is that they disappear when you refresh. I thought about using localStorage to fix this issue. I successfully created an array to store the items. Now, my goal is to display the items stored in tasks on the browser. However, I'm facing difficulty with the

document.addEventListener('DOMContentLoaded', getTasks)
and especially the getTasks() function. I even tried adding console.log('bonjour') for testing, but it doesn't seem to work.

Thank you for your help!

function getTasks() {
    console.log('bonjour')

    let tasks;
        if(localStorage.getItem('tasks') === null) {
            tasks = [];
        } else {
            tasks = JSON.parse(localStorage.getItem('tasks'));
        }
        tasks.forEach(task => {
            const html = `
            <li>
                <span>${task}</span>
                <i class="far fa-trash-alt delete"></i>
            </li>`
            list.innerHTML += html;
            console.log('hi')
        });
}
<!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">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
    <title>Todolist</title>
</head>
<body>
    <form action="" class="add">
        <h1>To do list</h1>
        <input type="text" id="name" name="add" placeholder="Enter name here"> 
    </form>

    <ul class="todos">
        <li>
            <span>marco</span>
            <i class="far fa-trash-alt delete"></i>
        </li> 
    </ul>

    <script src="app.js"></script>
</body>
</html>

Answer №1

function getTasks() {
  console.log('hello')

  let tasks
  if (localStorage.getItem('tasks') === null) {
    tasks = []
  } else {
    tasks = JSON.parse(localStorage.getItem('tasks'))
  }
  let list = document.getElementById('theList')
  tasks.forEach((task) => {
    const html = `
              <li>
                  <span>${task}</span>
                  <i class="far fa-trash-alt delete"></i>
              </li>`
    list.innerHTML += html
    console.log('hi')
  })
}

function storeValue(val) {
  if (!val) return
  if (!localStorage.getItem('tasks')) {
    let tasks = []
    tasks.push(val)
    localStorage.setItem('tasks', JSON.stringify(tasks))
    getTasks()
  } else {
    let tasks = JSON.parse(localStorage.getItem('tasks'))
    tasks.push(val)
    localStorage.setItem('tasks', JSON.stringify(tasks))
    getTasks()
  }
}

getTasks()
<!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">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  <title>To do list</title>
</head>

<body>
  <!-- <form action="" class="add"> -->
  <h1>To do list</h1>

  <input type="text" id="name" name="add" placeholder="Enter name here" onchange="storeValue(this.value)">

  <!-- </form> -->

  <ul class="todos" id="theList">
    <li>
      <span>marco</span>
      <i class="far fa-trash-alt delete"></i>
    </li>
  </ul>


  <script src="app.js"></script>
</body>

</html>

Give this code a try on your local setup to see the result. Make sure to test it as errors may occur. I have debugged the code for you.

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

Is it possible to set a click event or <A> link on an entire Ember component?

One of my Ember components has a tagName:'li' This is how the template appears: <div> title</div> <div> image </div> <div> text </div> The result is <li> blocks consisting of the elements above, displ ...

Tips for setting up Greasemonkey to automatically click on an unusual link on a particular website

I'm not a master coder by any means; I can handle some scripts but that's about it. Treat me like a total beginner, please! ;-) I want to automatically expand two specific links on a webpage using a GM Script. On a French dating site in the prof ...

What is the function of the next and back buttons in AngularJS?

I need assistance with creating next and previous buttons in Angular. As I am new to programming, I have written a program that works when using a custom array $scope.data = []. However, it doesn't work when I use $http and I would appreciate any help ...

Verify that all the input values within the class are empty using jQuery

Within this section, I have multiple input text fields all sharing the same class: <input type="text" class="MyClass"></input> <input type="text" class="MyClass"></input> <input type="text" class="MyClass"></input> My ...

Go through each .md document, transform them into HTML format, and dispatch them

I am using fs to read files in .md format and transform them into HTML files. Here is the code snippet I have written: fs = require('fs'); fs.readFile(__dirname + '/posts/react-v16.13.0.md', 'utf8', function (err, data) { i ...

What are the steps to effectively utilize <ul> for showcasing scrolling content?

I stumbled upon and found it to be a great inspiration for my project. I tried replicating the layout of the listed items on the site: .wrap { display: block; list-style: none; position: relative; padding: 0; margin: 0; border: ...

In Angular, iterate through each country and assign a value of 0 to any blank fields

My challenge is to dynamically generate empty objects with a value of 0 for each country in relation to all months. Check out my plunker example: http://plnkr.co/edit/6ZsMpdFXMvGHZR5Qbs0m?p=preview Currently, I only have data available for 2 months per co ...

Common mistakes encountered when utilizing webpack for react development

I'm currently following the exercises in Pro MERN Stack by Apress and have come across a webpack issue. Everything was running smoothly until I introduced webpack into the mix. Now, when I execute npm run compile, I encounter the following error: > ...

KendokendoNumericTextBox Unable to assign a value

After upgrading to the latest version of Kendo 2020, everything seems to be working smoothly except for the kendonumerictextbox control. I encountered an error when attempting to set a value to the kendonumerictextbox. $('#Taxes').data("kendoNu ...

The spinning wheel goes round and round while executing the location.reload() function

Currently, I am performing actions in my JavaScript function and then triggering a page refresh using location.reload(); I'm wondering if there is a straightforward method with jQuery to display a spinning wheel from the moment the page initiates the ...

Leveraging the power of JavaScript to reveal concealed div elements

I've got a collection of divs (five in total) with a hidden class applied to them in my CSS stylesheet. Each div also has its own unique ID. My goal is to use JavaScript to reveal these divs one by one. Here's an example of what I'm looking ...

Assessing the string to define the structure of the object

Currently, I am attempting to convert a list of strings into a literal object in Javascript. I initially tried using eval, but unfortunately it did not work for me - or perhaps I implemented it incorrectly. Here is my example list: var listOfTempData = [ ...

Having issues with my Bootstrap navigation dropdown - any suggestions on what I might be overlooking?

I'm having trouble getting the bootstrap dropdown and button to function properly when the menu collapses on tablet or mobile view. Below is my HTML code for the navigation: <nav class="navbar navbar-default navbar-fixed-top"> <div c ...

Change the dropdown header behavior from hovering over it to clicking on it

This snippet of code is integrated into our header to showcase the cart. Currently, the dropdown appears when hovering over it. Is there a way to adjust this so that the dropdown shows up when onclick? <a href="#header-cart" class="skip-link skip-cart ...

Leveraging Multiple Angular.js Controllers within a Shared DOM

As someone who is fairly new to Angular.js, I am currently working on integrating it into my Node.js application. While I have successfully created a RESTful API using Angular for a single controller, I am now looking to utilize two or more controllers wi ...

Sending form data using Ajax in codeigniter

I am encountering an error while attempting to submit a form using ajax in codeIgniter. Below is the view code that I have: <div class="form-group input-control"> <p id="error1" style="display: none; color: green"><b>Registered Succ ...

The error message "Uncaught TypeError: Cannot read property '0' of undefined" is triggered when using toDataURL

Recently diving into the world of JavaScript and facing a perplexing error. I must be overlooking some fundamental concept... apologies in advance. Here is the issue at hand. In my HTML file, this snippet of code is present: <div> <script type= ...

Utilize AngularJS to bind a variable and display an external HTML file without the need to open it in a browser

In my setup, I have two HTML Views - one is for application purposes and the other is for printing. Let's call them Application.html and PrintForm.html, respectively. Here is a snippet from Application.html: <!DOCTYPE html> <html> < ...

Changing the Flash message to an Alert message in Symfony2: A step-by-step guide

I've encountered a problem where the success message from an action method in Symfony2 Controller appears as a flash message, but I need to display it as an alert or dialogue message according to requirements. I have attempted various solutions witho ...

Tips for organizing parallel arrays with the provided data

I am having trouble with this question as it seems a bit vague to me. The concept appears more challenging than what we learned in class, and I'm not sure where to start. If someone could provide a simplified explanation, I would greatly appreciate it ...