Click here to Skip to main content
15,867,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to get a button to remove an item from an array.

This is what the array contains:
JavaScript
<pre>let products = [
    {
    name: 'Corin Bed',
    tag: 'Corin Bed-Vienna Dark Blue.jpg',
    price: 3500,
    inCart:0
},
{
    name: 'Miranda Bed',
    tag: 'Miranda Bed - Elephant & Anthracite.jpg',
    price: 2500,
    inCart:0
},
{
    name: 'Miuzza Bed',
    tag: 'Miuzza Bed - Vienna Cream.jpg',
    price: 2000,
    inCart:0
},
{
    name: 'Norma Bed',
    tag: 'Norma Bed - Vienna Beige.jpg',
    price: 3000,
    inCart:0
},
{
    name: 'Alpha Bedside',
    tag: 'ALPHA 1 DRAWER PEDESTAL-light oak.jpg',
    price: 1200,
    inCart:0
},
{
    name: 'Cyrus Bedside',
    tag: 'CYRUS 1 DOOR PEDESTAL - wedge.jpg',
    price: 1567,
    inCart:0
},
{
    name: 'Gamma Bedside',
    tag: 'GAMMA 2 DRAWER PEDESTAL-light oak.jpg',
    price: 900,
    inCart:0
},
{
    name: 'Gamma 3 Bedside',
    tag: 'GAMMA 3 DRAWER PEDESTAL-walnut.jpg',
    price: 1100,
    inCart:0
},
{
    name: 'Takka Bedside',
    tag: 'TIKKA 1 DRAWER PEDESTAL-mahogany.jpg',
    price: 800,
    inCart:0
},
{
    name: 'Alexia Chair',
    tag: 'ALEXA CHAIR - GRIJS.jpg',
    price: 1500,
    inCart:0
},
{
    name: 'Jean Chair',
    tag: 'JEAN STOOL - ANTRACIET.jpg',
    price: 1050,
    inCart:0
},
{
    name: 'Maxime Chair',
    tag: 'MAXIME CHAIR - ECRU.jpg',
    price: 1300,
    inCart:0
},
{
    name: 'Oscar Chair',
    tag: 'OSCAR CHAIR - ANTRACIET.jpg',
    price: 700,
    inCart:0
},
{
    name: 'Caden Coffee Table',
    tag: 'CADEN 120x60cm COFFEE TABLE-Light Oak.jpg',
    price: 1500,
    inCart:0
},
{
    name: 'Judy Coffee Table',
    tag: 'JUDY 100x55cm COFFEE TABLE-light oak.jpg',
    price: 1300,
    inCart:0
},
]



This is the display function:

JavaScript
<pre>function displayCart(){
    let cartItems = localStorage.getItem("productsIncart");
    cartItems = JSON.parse(cartItems);
    
let productContainer = document.querySelector(".products")
let cartCost = localStorage.getItem("totalCost");
    if(cartItems && productContainer){
        productContainer.innerHTML = '';
        let cartIndex = 0;
        Object.values(cartItems).map(item => {
            productContainer.innerHTML += `
            <div class = "product">
            <svg onclick="removeItem(event,${cartIndex++})" class="remove" clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="m12.002 2.005c5.518 0 9.998 4.48 9.998 9.997 0 5.518-4.48 9.998-9.998 9.998-5.517 0-9.997-4.48-9.997-9.998 0-5.517 4.48-9.997 9.997-9.997zm0 8.933-2.721-2.722c-.146-.146-.339-.219-.531-.219-.404 0-.75.324-.75.749 0 .193.073.384.219.531l2.722 2.722-2.728 2.728c-.147.147-.22.34-.22.531 0 .427.35.75.751.75.192 0 .384-.073.53-.219l2.728-2.728 2.729 2.728c.146.146.338.219.53.219.401 0 .75-.323.75-.75 0-.191-.073-.384-.22-.531l-2.727-2.728 2.717-2.717c.146-.147.219-.338.219-.531 0-.425-.346-.75-.75-.75-.192 0-.385.073-.531.22z" fill-rule="nonzero"/></svg>
                <img src="../assets/lookbook/${item.tag}">
                <span>${item.name}</span>
            </div>
            <div class="cost">${item.price}</div> 
            <div class="itemVolume">
            <svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="m22 12.002c0-5.517-4.48-9.997-9.998-9.997-5.517 0-9.997 4.48-9.997 9.997 0 5.518 4.48 9.998 9.997 9.998 5.518 0 9.998-4.48 9.998-9.998zm-8.211-4.843c.141-.108.3-.157.456-.157.389 0 .755.306.755.749v8.501c0 .445-.367.75-.755.75-.157 0-.316-.05-.457-.159-1.554-1.203-4.199-3.252-5.498-4.258-.184-.142-.29-.36-.29-.592 0-.23.107-.449.291-.591z" fill-rule="nonzero"/></svg>
            <svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="m2.009 12.002c0-5.517 4.48-9.997 9.998-9.997s9.998 4.48 9.998 9.997c0 5.518-4.48 9.998-9.998 9.998s-9.998-4.48-9.998-9.998zm8.211-4.843c-.141-.108-.3-.157-.456-.157-.389 0-.755.306-.755.749v8.501c0 .445.367.75.755.75.157 0 .316-.05.457-.159 1.554-1.203 4.199-3.252 5.498-4.258.184-.142.29-.36.29-.592 0-.23-.107-.449-.291-.591z" fill-rule="nonzero"/></svg>
            </div>
            <div class="volume"><span>${item.inCart}</span></div> 
            <div class="totalCost">
            <span class ="total">R${item.inCart * item.price}</span>
            </div> 
            `
        });

        productContainer.innerHTML += `
        <div class="basketTotalContainer">
        <h4 class="basketTotalTitle">
          Cart Total
        </h4>
        <h4 class="basketTotal">
            R${cartCost}
        </h4>
      </div>
        `
    }
}
onloadCartNumbers()
displayCart()


What I have tried:

This is my function that supposed to remove the item on button click, but its not working:

function removeItem(event, i){
    let cartItemsJson = localStorage.getItem("productsIncart");
    let cartItems = JSON.parse(cartItems);
    cartItems.splice(i)
    localStorage.setItem('productsIncart', JSON.stringify(cartItems));

    displayCart()
}
Posted
Updated 9-Aug-22 3:27am
v4
Comments
Richard Deeming 9-Aug-22 8:40am    
cartItems.splice(i)

According to the documentation, that will remove all items from the array starting at the specified index.
Array.prototype.splice() - JavaScript | MDN[^]

Are you sure you didn't mean cartItems.splice(i, 1); instead?

1 solution

Your displayCart() method is iterating over cartItems to render the HTML, yet your removeItem code is removing an item from the products variable? Shouldn't your method be:
JavaScript
function removeItem(event, i){
    let cartItemsJson = localStorage.getItem("productsIncart");
    let cartItems = JSON.parse(cartItemsJson);
    cartItems.splice(i)
    localStorage.setItem('productsIncart', JSON.stringify(cartItems));

    displayCart()
}

The other issue is that in your HTML code for the click even you're referencing an i variable which doesn't seem to exist:
HTML
onclick="removeItem(event,i)"

This i variable probably won't have a value here, so you may get undefined passed into your function. Instead, you might need to declare a variable outside of your loop and interpolate it into the HTML:
JavaScript
var cartIndex = 0;
Object.values(cartItems).map(item => {
  productContainer.innerHTML += `
  ..
  <svg onclick="removeItem(event,${cartIndex++})"
  ..
 
Share this answer
 
v4
Comments
sheldon aldridge 9-Aug-22 6:52am    
Thanks for that Chris, I tried implementing what you mentioned but it does not seem to work, I updated my code with what you mentioned above as I get an error of
Uncaught ReferenceError: cartItems is not defined
at removeItem (add-to-cart.js:212:5)
at SVGSVGElement.onclick (cart.html:102:2)
Chris Copeland 9-Aug-22 8:15am    
Sorry I forgot I omitted the part where you actually grab the cart items from the local storage. I've updated my answer accordingly.
sheldon aldridge 9-Aug-22 9:23am    
Thank you, am I doing something wrong here,because I get this error
add-to-cart.js:213 Uncaught ReferenceError: Cannot access 'cartItems' before initialization
at removeItem (add-to-cart.js:213:32)
at SVGSVGElement.onclick (cart.html:102:2)
Chris Copeland 9-Aug-22 12:24pm    
My bad again, I had a typo in the code. I had suggested JSON.parse(cartItems); instead of JSON.parse(cartItemsJson). The error you got though told you the exact problem and which line to look at so you probably could have figured that out yourself!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900