0

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 class="product-header cart"><img src="${image}" alt="" /></div>
        <div class="product-content">
            <h3 class="product-title" id="product-title">
            ${title} 
            </h3>
            <div class="product-description">
                <ul class="product-description-text cart">
                    <li>Color: <span id="${spanid}">${color} </span></li>
                    <li>Size: ${size} </li>
                    <li>Quantity: <input type="number" class="product-description-quantity" min="1" placeholder="2" value="2"></li>
                </ul>
                <p class="product-description-price" id="price1">
                ${price} 
                </p>
                **<a href="#" class="product-description-add cart-remove">Remove<i class="fas fa-trash"></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 class="product-header cart" id="${id}"><img src="${image}" alt="" /></div>
        <div class="product-content">
            <h3 class="product-title" id="product-title">
            ${title} 
            </h3>
            <div class="product-description">
                <ul class="product-description-text cart">
                    <li>Color: <span id="${spanid}">${color} </span></li>
                    <li>Size: ${size} </li>
                    <li>Quantity: <input type="number" class="product-description-quantity" min="1" placeholder="2" value="2"></li>
                </ul>
                <p class="product-description-price">
                ${price} 
                </p>
                <a href="#" onclick="lsdel(\'newProduct\',\'+cartProducts[i].id+\');" class="product-description-add cart-remove">Remove<i class="fas fa-trash"></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);  
        }
    }
}
13
  • 3
    Read the array from local storage, find the index of the matching element with array.findIndex(), use array.splice() to remove it, then write the array back to local storage. Commented Jan 11, 2022 at 20:02
  • is spanid the ID of the product? If so, why is it only on the span tag around color? Commented Jan 11, 2022 at 20:02
  • @Kinglish no, the spanid is one element i needed to be stored on localstorage to allow me to style the div when i display it to the user, but it's no related to the product id Commented Jan 11, 2022 at 20:05
  • thanks @Barmar i'll try to do it Commented Jan 11, 2022 at 20:05
  • You can also use array.filter with the predicate that excludes the item you want to remove and then save the filtered array. Commented Jan 11, 2022 at 20:06

1 Answer 1

2

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);
    }
  }
}

Sign up to request clarification or add additional context in comments.

11 Comments

Thanks for your answer but I can't manage to make it work properly, the index keeps on being '-1' each time i click on the remove button. Your code i'm sure that works perfectly but the problem must be something that i'm not being able to identify and resolve :||
addProduct() isn't putting the id into newItem.
No, the id is being added to newItem, this is an example of an element of the array stored on localstorage: 0: {id: 1, title: "Adidas Hoodie", image: "http://**/img/products/1.jpg", color: "gray",…} color: "gray" id: 1 image: "http://**/img/products/1.jpg" price: "$39.99" size: "M" spanid: "sp1" title: "Adidas Hoodie" but index is still -1 :@
let newItem = { 'title': getTitle, 'image': getImage, 'color': getColor, 'size': getSize, 'price': getPrice, 'spanid': getSpan, }; where is the id in that?
I'm looking at the code in function addProduct(event).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.