I'm working with an array called cartarray that has the following format.
1: {id: "1510-01-312-3501-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514542566148", name: "AIRPLANE UTILITY", price: "$90", quantity: "1"}
2: {id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "3"}
3: {id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "$43", quantity: "1"}
The HTML structure below is dynamically created based on the information in the array above.
cartarry.products.forEach(function(element) {
var id = element.id;
var itemname = element.name;
var itemprice = element.price;
var itemcard = `
<div class="product" id="${id}">
<div class="product-image">
<img src="https://s.cdpn.io/3/dingo-dog-bones.jpg">
</div>
<div class="product-details">
<div class="product-title">Dingo Dog Bones</div>
<p class="product-description"> ${itemname}</p>
</div>
<div class="product-price">${itemprice}</div>
<div class="product-quantity">
<input type="number" value="2" min="1">
</div>
<div class="product-removal">
<button class="remove-product">
Remove
</button>
</div>
<div class="product-line-price">25.98</div>
</div>
`;
itemcontainer.innerHTML += itemcard;
})
My goal is to remove the clicked item from the array, so I attempted the following script:
var items = cartarry.products;
$('.product').on('click', function(element) {
console.log(this.id)
var index = items.indexOf(this);
console.log(index)
var i = items.indexOf(this);
if (i != -1) {
items.splice(i, 1);
}
})
However, regardless of which item I click, the 'index' value keeps returning as -1 preventing item deletion. How can I resolve this issue and successfully delete the clicked item from the array?