In my JavaScript code, I am trying to increment the value of items by adding a label input from the user. I have set up an input label and button to receive and store the user input values. In my array, I have five items with unique Id's. However, I am facing an issue where the function is not able to push and concatenate the existing values together, instead of creating a new array element.
add.addEventListener('click', function() {
let basket = JSON.parse(localStorage.getItem('basket')); // Retrieve data from local storage
let elementimageUrl = element.imageUrl;
let elementId = element._id;
let elementName = element.name;
let elementPrice = element.price;
let add2 = document.getElementById("userinput").value;
let yInt = Number.parseInt(add2);
console.log(yInt);
let elementQuantity = yInt;
console.log(elementQuantity);
if (!basket) {
basket = [];
}
const itemIndexInBasket = basket.findIndex(basketEntry => basketEntry.elementId === elementId);
if (itemIndexInBasket !== -1) {
basket[itemIndexInBasket].elementQuantity++;
} else {
basket.push({elementId, elementName, elementPrice, elementQuantity, elementimageUrl});
}
localStorage.setItem('basket', JSON.stringify(basket));
})
This code snippet demonstrates how the button can add all values to an array. However, I am looking for a way to increment the existing elementQuantity value instead of creating a new array element.