Home > Enterprise >  How to delete an item from an array from localstorage onclick
How to delete an item from an array from localstorage onclick

Time:01-13

I have the following code. It stores the info on localstorage each time the user clicks on an "add to cart" button:

let addCartItemButtons = document.getElementsByClassName('product-description-add')
for (let i = 0; i < addCartItemButtons.length; i  ){
    let button = addCartItemButtons[i]
    button.addEventListener('click', addProduct)
} 

function addProduct(event) {
    let buttonClicked = event.target
    let getTitle = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-title').innerText
    let getImage = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-header img').src
    let getColor = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li span').innerText
    let getSize = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li select').value
    let getPrice = buttonClicked.parentElement.parentElement.querySelector('.product-description-price').innerText
    let getSpan = buttonClicked.parentElement.parentElement.querySelector('li span').getAttribute('id')

    let oldItems = JSON.parse(localStorage.getItem('newProduct')) || [];
    let newItem = {
        'title': getTitle,
        'image': getImage,
        'color': getColor,
        'size': getSize,
        'price': getPrice,
        'spanid': getSpan,
    };
    
    oldItems.push(newItem);
    localStorage.setItem('newProduct', JSON.stringify(oldItems));
}

Then, i have a code that allows me to display the data the user have locally stored by creating divs and displaying the info:

let cartProducts = JSON.parse(localStorage.getItem("newProduct"))
for(let i = 0; i < cartProducts.length; i  ){
    let newCartProduct = document.createElement('div')
    newCartProduct.classList.add('product')
    newCartProduct.classList.add('cart')
    const image = cartProducts[i].image
    const title = cartProducts[i].title
    const spanid = cartProducts[i].spanid
    const color = cartProducts[i].color
    const size = cartProducts[i].size
    const price = cartProducts[i].price
    let newCartProductContent = `
    <div ><img src="${image}" alt="" /></div>
        <div >
            <h3  id="product-title">
            ${title} 
            </h3>
            <div >
                <ul >
                    <li>Color: <span id="${spanid}">${color} </span></li>
                    <li>Size: ${size} </li>
                    <li>Quantity: <input type="number"  min="1" placeholder="2" value="2"></li>
                </ul>
                <p  id="price1">
                ${price} 
                </p>
                **<a href="#" >Remove<i ></i></a>**
            </div>
        </div>`
    newCartProduct.innerHTML = newCartProductContent
    let cartItems = document.getElementsByClassName('products_container_first-row')[0]
    cartItems.append(newCartProduct)
}

So what i need to do now is to create a function that allows me to delete the data that it's the same which is on localstorage, each time that the user clicks on a "remove" button (in the above code is the line which has the ** ** at beginning and ending), but i cant figure out how to do this. Any ideas? Thanks!

UPDATE: i've come to this code but i get -1 as index for each element:

let addCartItemButtons = document.getElementsByClassName('product-description-add')
for (let i = 0; i < addCartItemButtons.length; i  ){
    let button = addCartItemButtons[i]
    button.addEventListener('click', function(event){
        let buttonClicked = event.target
        let getTitle = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-title').innerText
        let getImage = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-header img').src
        console.log(getImage)
        let getColor = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li span').innerText
        let getSize = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li select').value
        let getPrice = buttonClicked.parentElement.parentElement.querySelector('.product-description-price').innerText
        let getSpan = buttonClicked.parentElement.parentElement.querySelector('li span').getAttribute('id')
        console.log(getSpan)
    
        let oldItems = JSON.parse(localStorage.getItem('newProduct')) || [];
        let newItem = {
            'id': i 1,
            'title': getTitle,
            'image': getImage,
            'color': getColor,
            'size': getSize,
            'price': getPrice,
            'spanid': getSpan,
        };
        
        oldItems.push(newItem);
        localStorage.setItem('newProduct', JSON.stringify(oldItems));
    })
} 

let cartProducts = JSON.parse(localStorage.getItem("newProduct"));
for(let i = 0; i < cartProducts.length; i  ){
    let newCartProduct = document.createElement('div')
    newCartProduct.classList.add('product')
    newCartProduct.classList.add('cart')
    console.log(newCartProduct)
    const id = cartProducts[i].id
    const image = cartProducts[i].image
    const title = cartProducts[i].title
    const spanid = cartProducts[i].spanid
    const color = cartProducts[i].color
    const size = cartProducts[i].size
    const price = cartProducts[i].price
    let newCartProductContent = `
    <div  id="${id}"><img src="${image}" alt="" /></div>
        <div >
            <h3  id="product-title">
            ${title} 
            </h3>
            <div >
                <ul >
                    <li>Color: <span id="${spanid}">${color} </span></li>
                    <li>Size: ${size} </li>
                    <li>Quantity: <input type="number"  min="1" placeholder="2" value="2"></li>
                </ul>
                <p >
                ${price} 
                </p>
                <a href="#" onclick="lsdel(\'newProduct\',\' cartProducts[i].id \');" >Remove<i ></i></a>
            </div>
        </div>`
    newCartProduct.innerHTML = newCartProductContent
    let cartItems = document.getElementsByClassName('products_container_first-row')[0]
    cartItems.append(newCartProduct)
}
function lsdel(storage_name, value){
    if (localStorage.getItem(storage_name) === null) { 
    } else {        
        var ls_data = JSON.parse(localStorage.getItem(storage_name));
        var index   = ls_data.indexOf(value);
        console.log("selected index:" index);
        if(index == -1){
        // if not matched selected index    
        } else {
            // is matched, remove...
            ls_data.splice(index, 1);
            localStorage.setItem(storage_name, JSON.stringify(ls_data));
            console.log(ls_data);  
        }
    }
}

CodePudding user response:

value is the ID of an element, but ls_data is an array of objects, not IDs. So ls_data.indexOf(value) will not find the object in the array. And even if value were an object, this wouldn't work because object equality is based on identical objects in memory, not comparing contents.

You need to use findIndex to match the id property of an array element.

function lsdel(storage_name, value) {
  if (localStorage.getItem(storage_name) === null) {} else {
    var ls_data = JSON.parse(localStorage.getItem(storage_name));
    var index = ls_data.findIndex(({id}) => id == value);
    console.log("selected index:"   index);
    if (index == -1) {
      // if not matched selected index    
    } else {
      // is matched, remove...
      ls_data.splice(index, 1);
      localStorage.setItem(storage_name, JSON.stringify(ls_data));
      console.log(ls_data);
    }
  }
}

  •  Tags:  
  • Related