TransWikia.com

Click function is removing end of localStorage items not at Index in JavaScript

Stack Overflow Asked on November 10, 2021

My current code adds and removes items from a list, then the user can save the list and I want the user to be able to remove items from the saved list, this is done through a function removeItemsLocalStorage() but what is happening is that the localStorage items are getting removed from the end and not at the index, I am a little confused as to how to get the index position of the localStorage items, which is an array. This is more of a learning exercise process for me.

Code is:

let domElements = {
    app: document.createElement('DIV'),
    heading: document.createElement('H1'),
    header: document.createElement('DIV'), 
    hero: document.createElement('DIV'),
    newDiv: document.createElement('DIV'),
    errorMessage: document.createElement('P'),
    grid: document.createElement('DIV'), 
    saveList: document.createElement('UL')
}

function domAttributes() {
    domElements.app.classList.add('app');
    document.body.append(domElements.app);
    domElements.heading.textContent = 'Shopping';
    domElements.newDiv.innerHTML = '<p>This is the text of the element</p>';
    domElements.heading.insertAdjacentElement("afterend", domElements.newDiv);
    domElements.errorMessage.innerHTML= 'Error type something in!';
    domElements.heading.insertAdjacentElement("beforeend", domElements.errorMessage);
    domElements.errorMessage.style.color = 'red';
    domElements.errorMessage.style.display = 'none';
    domElements.app.append(domElements.heading);
    domElements.grid.classList.add('grid');
    domElements.saveList.classList.add('saveUl');
    domElements.app.append(domElements.grid);
}

domAttributes();

var data = [
    "Monday", 
    "Tuesday",
    "Wednesday"
];

let gridItems = [
    '<div id="item1" class="item"></div>',
    '<div id="item2" class="item"></div>'
];

var loopElement = 
    {
        image: `<div class="innerElement">Head Test</div>`,
        name: 'Element'
    };

function gridItemLooper(ele) {
    let items = ''; 
    for (let i = 0; i < ele.length; i++) {
        items += ele[i];
    }
    return items;
}

const gridInnerElement = gridItemLooper(gridItems);        
domElements.grid.innerHTML = gridInnerElement;  

function looper() {
let loopImage = '';
for (let i = 0; i < 1; i++) {
    loopImage += loopElement.image;
    }
    return loopImage;
}    


function heroElement() {
    domElements.hero.textContent = 'Hero';
    domElements.hero.classList.add('hero');
    domElements.hero.innerHTML = '<div class="innerElement">Inner Element</div>';
    domElements.hero.setAttribute(
     "style", "font-size: 32px; font-style: bold; background-color:#000000; color: white; width: 100%; height: auto; padding: 20px; font-family: sans-serif"); 
     domElements.app.append(domElements.hero);
}

function itemArray(ele) {
    let items = ''; 
    for (let i = 0; i < ele.length; i++) {
        items += `<li>${ele[i]} <button type='button' class='removeItem'>Remove Item</button> </li>`;
    }
    return items;
}

function layOut() {
    const ui = heroElement();
}

layOut();

function addItemFunction (ele) {
    const addButton = document.getElementById('addButton');
    const input = document.getElementById('input').value;
    
    if (input.length > 0 ) {
        data.push(input);  
        htmlInside(data); 
        domElements.errorMessage.style.display = 'none';
    } else {
        domElements.errorMessage.style.display = 'block';
    }
    
}

function removeItemFunction() {
    data.pop(data);    
    htmlInside(data);
}

function removeItems() {
    const listUl = domElements.app.querySelector('.listItems');
    listUl.addEventListener('click', (event) => {
        if (event.target.tagName == 'BUTTON') {
          let li = event.target.parentNode;
          let ul = li.parentNode;
          ul.removeChild(li);         
          var ele = li.textContent.split(" ")[0];
          var index = data.indexOf(ele);
          data.splice(index, 1);
          console.log(data); 
        }
      });
}

function removeItemsLocalStorage() {
    const listUl = domElements.app.querySelector('.saveUl');
    listUl.addEventListener('click', (event) => {
        if (event.target.tagName == 'BUTTON') {
          let li = event.target.parentNode;
          let ul = li.parentNode;
          ul.removeChild(li);
          let displayItems = JSON.parse(localStorage.getItem("Shopping List"));
          var ele = li.textContent;
          var index = displayItems.indexOf(ele);
          alert(ele);
          displayItems.splice(index, 1);
          localStorage.setItem('Shopping List', JSON.stringify(displayItems));
        }
    });
}

domElements.app.insertAdjacentElement("beforeend", domElements.saveList);
let displayItems = JSON.parse(localStorage.getItem("Shopping List"));

if (localStorage.length > 0) {
    domElements.saveList.innerHTML = displayArray(displayItems);
}

function saveItems(ele) {
    localStorage.setItem('Shopping List', JSON.stringify(ele));
    let displayItems = JSON.parse(localStorage.getItem("Shopping List"));
    domElements.saveList.innerHTML = displayArray(displayItems);
}

function clearItems(ele) {
    localStorage.clear(ele);
    domElements.saveList.innerHTML = localStorage.getItem('Shopping List');
}

function displayArray(ele) {
    let items = ''; 
    for (let i = 0; i < ele.length; i++) {
        items += `<li>${ele[i]} <button type='button' class='removeItem'>Remove Item</button></li> `;
    }
    return items;
}

function clickEvents() {
    addButton.addEventListener('click', function () {
        addItemFunction();
    });

    removeButton.addEventListener('click', function () {
        removeItemFunction();
    });
    
    saveButton.addEventListener('click', function () {
        saveItems(data);
    });
    clearButton.addEventListener('click', function () {
        clearItems(data);
    });
}

function htmlInside(data){
    let getHtml = `
        <ul class="listItems">
            ${itemArray(data)}    
        </ul>
        <input type='input' id='input'></input><button type='button' id='addButton'>Add item</button><button id='removeButton'>Remove item</button><button id='saveButton'>Save list</button><button id='clearButton'>clear list</button>
    `
    document.querySelector('.hero').innerHTML = getHtml;
    removeItems();
    clickEvents();
 }  
 
 htmlInside(data);
 removeItemsLocalStorage(data);

One Answer

In the end this code below worked, I had to use the split() method.

function removeItemsLocalStorage() {
    const listUl = domElements.app.querySelector('.saveUl');
    listUl.addEventListener('click', (event) => {
        if (event.target.tagName == 'BUTTON') {
          let li = event.target.parentNode;
          let ul = li.parentNode;
          ul.removeChild(li);
          let displayItems = JSON.parse(localStorage.getItem("Shopping List"));
          var ele = li.textContent.split(" ")[0];
          var index = displayItems.indexOf(ele);
          displayItems.splice(index, 1);
          localStorage.setItem('Shopping List', JSON.stringify(displayItems));
        }
    });
}

Answered by Sole on November 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP