Delete the task that was selected from the local storage

I am struggling to remove a task from local storage. I have already implemented a function to delete the task from the DOM, but I'm unsure how to specifically remove that object from local storage in order to save the changes. It seems like I need to retrieve and parse data from local storage, iterate over the keys, and delete the item that has the same "title". However, if I remove it from local storage, I face a dilemma as I cannot iterate.

<h1 class="text-center mt-5 mb-5">MY TO-DO LIST</h1>
<div class="container">
<div class="row">
  <div class="col-4">
    <form id="todoForm">
      <div class="mb-3">
        <label class="form-label">Task Title</label>
        <input type="text" required name="title" class="form-control">
      </div>
      <div class="mb-3">
        <label  class="form-label">Task Description</label>
        <textarea name="description" required class="form-control" placeholder="Task body" cols="30" rows="10"></textarea>
      </div>
      <button type="submit" class="btn btn-primary">Add Task!</button>
    </form>
  </div>
  <div class="col-8">
    <div class="row" id="taskList">
    </div>
  </div>
</div>
    const myToDoList = {
    selector: null,
    form: null,
    containerSelector: null,
    container: null,
    init (selector, container) {
        if(typeof selector === "string" || selector.trim() !== "") {
            this.selector = selector;
        }
        if(typeof container === "string" || container.trim() !== "") {
            this.containerSelector = container;
        }
        this.getForm();
        this.getHTMLElement();
    },
    getForm () {
        let formElement = document.querySelector(this.selector);
        this.form = formElement;
        formElement.addEventListener("submit", event => {
            event.preventDefault();
            event.stopPropagation();
            const data = {};
            formElement.querySelectorAll("input, textarea")
                .forEach((item) => {
                    data[item.name] = item.value;
                })
            const savedData = this.saveData(data);
            this.renderItem(savedData);
        })
    },

    getHTMLElement() {
        const todoContainer = document.querySelector(this.containerSelector);
        this.container = todoContainer;
        document.addEventListener("DOMContentLoaded", event => {
            event.preventDefault();
            event.stopPropagation();
            const tasks = JSON.parse(localStorage.getItem(this.selector));
            if(!tasks) return "Error!";
            tasks.map(taskItem => {
                this.renderItem(taskItem);
            })
        })
    },

    saveData(data) {
        let dataFromStore = localStorage.getItem(this.selector);
        if(!dataFromStore) {
            const array = [];
            array.push(data);
            localStorage.setItem(this.selector, JSON.stringify(array));
        }
        if(dataFromStore) {
            dataFromStore = JSON.parse(dataFromStore);
            dataFromStore.push(data);
            localStorage.setItem(this.selector, JSON.stringify(dataFromStore));
        }
        return data;
    },

    renderItem(data) {
        const title = data.title;
        const description = data.description;
        const wrapper = document.createElement("div");
        wrapper.classList.add("col-4");
        wrapper.innerHTML = `<div class="taskWrapper">
            <div class="taskHeading">${title}</div>
            <div class="taskDescription">${description}</div>
            <button class="delBtn" data-del="delete">Delete</button>
            </div>`;
        this.container.appendChild(wrapper);
    },

    deleteTask() {
        document.addEventListener('click', e => {
            let targetBtn = e.target.getAttribute("data-del");
            if(targetBtn === "delete") {
                // Delete from DOM
                let titleTsk = e.target.parentNode.firstElementChild;
                e.target.parentNode.parentNode.remove();
                // ============== //
                let taskTitle = titleTsk.innerHTML;
                let foundTask = JSON.parse(localStorage.getItem("#todoForm"));
                console.log(foundTask);
            }
        })
    }
}
myToDoList.init("#todoForm", "#taskList");
myToDoList.deleteTask();

Answer №1

After some searching, I managed to figure it out:

        removeItem() {
        document.addEventListener('click', e => {
            const buttonClicked = e.target.getAttribute("data-del");
            if(buttonClicked === "delete") {
                const taskTitle = e.target.parentNode.firstElementChild;
                e.target.parentNode.parentNode.remove();
                const taskName = taskTitle.innerHTML;
                const savedTasks = JSON.parse(localStorage.getItem("#todoForm"));
                const indexToDelete = savedTasks.findIndex(obj => {
                    return obj.title === taskName;
                });
                savedTasks.splice(indexToDelete, 1);
                localStorage.setItem(this.selector, JSON.stringify(savedTasks));
            }
        });
    }

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

Tips on selecting specific data from a nested JSON array based on conditions and fetching just one value from the initial filtered result with Javascript (designed for Google Sheets)

Utilizing the TMDB API for retrieving movie data and integrating it into a Google Sheet. The original Google Sheet was revamped from Reddit user 6745408's "MediaSheet 3.0". This sheet incorporates a Javascript-based script. By following the patterns/c ...

Sort through the JSON data and showcase it in a gridded format

I need assistance with displaying data from a JSON object in a grid based on user selections. The user should be able to select a year and make from a dropdown menu, and the corresponding data should then be filtered and displayed in a grid. For example, i ...

Tips for triggering a method when clicking instead of using v-for in Vue.js

I need help arranging an array of objects based on their ratings. Currently, I am able to display the items from highest to lowest rating using the v-for method. But, I would like to first display the objects in their original order and then have a button ...

Stopping an endless loop in JavaScript by pressing a key on the keyboard can be a useful

I've been working on creating a JavaScript game and am currently tackling the challenge of implementing gravity. One crucial aspect I need to address is creating an infinite loop without causing the browser to crash. Is there a way for me to include a ...

Generating data within an express route (with the use of socket.io-client)

Recently, I made the decision to refactor my code in order to separate the front and back end, which were previously combined into one service. However, I am now facing an issue where I need the web server to emit data to the data server after validation. ...

Issue with Nuxt: Property accessed during rendering without being defined on the instance

As I attempt to create cards for my blog posts, I encountered an issue with a Post component in my code. The cards are displaying like shown in the picture, but without any text. How do I insert text into these cards? Currently, all the text is within attr ...

I need assistance with an issue on my Google Dev Console, as it keeps showing an error stating that ".getcontext is

Looking for some assistance here as my development console keeps displaying an error: Uncaught TypeError: canvas.getContext is not a function. Here is the problematic code snippet: `var canvas = document.createElement; var c = canvas.getContext("2d&qu ...

How can Chrome's display:none latency be eliminated?

My Chrome extension is designed to alter a third-party web page by removing a button and adding two new HTML elements. The process involves observing the URL of the current tab and executing an HTML injection if it matches the specified regex pattern. Desp ...

Assign specific classes to the rows and overall table by extracting information from the first row and first column of the table

My goal is to utilize jQuery in order to dynamically assign classes to the rows and columns of a table based on the classes of the first row and column. For instance: The current HTML code I have is as follows: <table class="numAlpha" border="1"> ...

Retrieving an element based on user input's value

Having trouble comparing multiple input elements to another input by matching values. The problem arises when attempting to match values with user input on the page load, unlike when the inputs already have values. Check out the JSFIDDLE here <script ...

What rules should be followed in Python when it comes to using nested parentheses in functions?

Currently in the process of deleting my account from this platform, I am intentionally adding unnecessary content to this post. Please refrain from restoring the previous content. - Original Poster ...

I only need one array from a map that returns two promises with arrays

Currently, I am working on optimizing the process of adding food and drink to an order simultaneously. To achieve this, I have created a promise that resolves when both actions are completed. These promises are then nested within another promise, which res ...

How to activate a function or event upon closing a browser tab with JavaScript

How can a function be triggered when a user closes the browser tab, preventing it from closing immediately and instead displaying a popup prompting the user to either proceed to another page or close the tab? Scenario: In the event that a user attempts t ...

Why won't my AngularJS Google Maps marker trigger any events?

My issue is with the marker event not working on a UI Google Map. I am using this link. Here is my view setup: <ui-gmap-markers models="mapResult" fit="true" idkey="mapResult.id" coords="'form_geo'" click="'onclick'" events="mapRe ...

How to pass children and additional arguments to a React/NextJS component

Currently, I am utilizing NextJS with a global PageLayout wrapper that is responsible for setting the head and creating the wrapping divs for all my pages. However, I am facing a challenge as I attempt to set a custom title tag for each page. This task req ...

Can you explain how I can declare a variable to store a scraped element in Puppeteer?

const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ headless: false, defaultViewport: null }) const page = await browser.newPage() await page.goto('https://www.supre ...

Passing an arrow function as props results in an error of undefined

When passing event handler functions as props to child components, regular functions are received but not fat arrow functions. import React, { Component } from "react"; export default class FruitClass extends Component { bananaEvents = { color: thi ...

Creating a dynamic interaction between HTML forms and JavaScript using the onsubmit event handler

Having trouble getting my JavaScript file to fire when clicking the submit button on my simple HTML form. Can anyone provide some assistance? **UPDATED CODES Here is a snippet of my condensed HTML file: <html> <form name="form01" id="form01" ac ...

When attempting to call XML, it fails to load and returns an undefined error

I'm encountering an error when trying to load my content: Members.html:9 Uncaught ReferenceError: loadXMLDoc is not defined at HTMLButtonElement.onclick Here is my HTML code: <p><button onclick="loadXMLDoc()"> Load Table </ ...

Is it possible for me to retrieve a variable that is contained within a function?

I have extracted data from 2 separate JSON files and now I am looking to divide one by the other. How can this be achieved? Specifically, I aim to divide the 'sugString' with the 'htmlString'. Following this operation, I want to insert ...