Increase the value of an array element based on the input from a specified label

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.

https://i.sstatic.net/KhiF3.png

Answer №1

  • Your solution
// Check if item is already in the basket
const itemIndexInBasket = basket.findIndex(basketEntry => basketEntry.elementId === elementId);
if (itemIndexInBasket !== -1) {
  basket[itemIndexInBasket].elementQuantity++;
} else {
  basket.push({elementId, elementName, elementPrice, elementQuantity, elementimageUrl});    // Add new item to basket
} 

Cause of the problem

The elementId you are comparing is undefined in

basketEntry.elementId === elementId

How I attempted to investigate the issue...

  • Reviewing your code

https://i.sstatic.net/eNM4T.png

  • Result

https://i.sstatic.net/JskoG.png

Explanation

  • This is why a new value is appended to the existing one, as the elementQuantity is the only defined value (others are undefined).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue of JQuery Mobile not recognizing HREF links when combined with Javascript

I am facing a challenge with my button functionality that is supposed to open a panel. However, there seems to be an interference caused by my JavaScript code. The panel contains a notifications center and in order to retrieve the notifications, I have to ...

What is the reason for sending back an array with no elements in AJAX

I am facing a perplexing issue where my function is returning an empty array when it should contain values. This has me scratching my head, as initially the array 'storearray1' does contain values, but upon subsequent usage, it appears empty. I&a ...

Initially Missing Child Props in Parent Component

I am currently working on an application that utilizes a nutrition API to fetch information such as calories and more. One of the key features I am developing is the ability for users to set their daily calorie target along with the percentage breakdown fo ...

What could be causing the absence of ReactDOM in my hello world application?

I have recently started learning Reactjs and I'm attempting to run a hello world program in the browser. However, I encountered an error which reads: react-dom.min.js:12 Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_ ...

What is the best method to position a modal in the exact center of the screen?

Is there a way to position the modal at the center of the screen? I have tried implementing this HTML and JavaScript code. Interestingly, it works fine in Chrome console but fails when I try to refresh the page. $('.modal').css('top', ...

Issue with Counting Digg Button Clicks

I can't figure out why the digg button counter isn't working. I followed the instructions but... The website in question is: . I implemented the code exactly as explained here: But the counter remains at 0. Has anyone encountered a similar iss ...

What is the best way to showcase my subscription form on a web browser?

I am encountering an issue with my code. My goal is to generate a subscribe form modal. Although I have incorporated the subscribe form in my HTML document, upon running the code in the browser, the subscribe section is not visible. Can anyone offer assist ...

Activate the jQuery UI datepicker with a trigger

Within my code, I have a span element that displays a date in the format mm/dd/yyyy. <span class="editableDateTxt">06/10/2014</span> My goal is to have an inline editable date popup or utilize jQuery UI's datepicker when this span elemen ...

What happens when the user closes a notification in GetUIkIt 3?

Is there a way to detect when a UIKit notification has been closed? The UIkit notification plugin () mentions that it has a close event. Can this be utilized for notifications triggered programmatically as shown below? e.g. UIkit.notification({ mess ...

Tips for querying multiple elements that share a common ID and verifying if the input has been modified

I have a series of text inputs that share a common id prefix but differ slightly at the end. Whenever a user enters text in any of these input fields, I want to trigger a function. Currently, I have this functionality implemented with the following code: ...

Ways to update a component when the value of a Promise is altered

I am struggling with Vue component re-rendering due to a problem related to consuming data from a Promise. The data is fetched and stored under the specific property chain (visualData.layout.cube...), where I assign values to DATA properties (such as label ...

upgrade multidimensional matrix

I have a unique array with character names from the popular TV show, The Simpsons (Homer, Marge, and Bart). I've used a foreach loop to display the keys and values. My goal is to have two input boxes next to each character name that allow for updating ...

In Angular, link a freshly loaded ".js" controller to a newly loaded "html" view following the bootstrapping process on ngRoutes

As a newcomer to Angular, I have been experimenting with loading dynamic views using ngRoutes (which is very cool) along with their respective .js controllers for added functionality. However, I am encountering difficulties in binding them together after b ...

Angular 2 Aot Issue: CRITICAL ERROR: CALL_AND_RETRY_LAST Allocation unsuccessful - JavaScript heap exhausted

Encountered an issue while running Angular 2 AOT rollup: <--- Last few GCs ---> 144518 ms: Mark-sweep 1317.0 (1404.4) -> 1317.0 (1404.4) MB, 1522.9 / 0.0 ms [allocation failure] [GC in old space requested]. 146029 ms: Mark-sweep 1317.0 (1404 ...

Form submission using AJAX is either limited to one-time use or requires a page refresh to update

One of the challenges I encountered while working on a wiki app built in Rails was updating a table of collaborators using JavaScript. I wanted to add collaborators from an existing users' table without having to refresh the page every time. Initially ...

Skipping MongoDB in loop operations in a Node.js environment.The original text was modified to

Apologies for the beginner question (The following code is related to express framework and mongoose DB) I am attempting to iterate through the array 'Users' which contains usernames. Then, I am trying to match them in the mongoose database to r ...

Learning about a basic sorting algorithm that analyzes and compares different values

While on the hunt for a simple jQuery sorting script, I stumbled upon this gem online: $(function() { $('ol').each(function() { var matches = $('li', this).filter(function() { // Each item var text = $(this).te ...

Utilizing jQuery to invoke a function at the conclusion of another function's execution

Can someone explain how jQuery can achieve the following? $('.test').css().otherThing...... etc I'm attempting to accomplish this with prototype: var myPrototype = function () {}; myPrototype.prototype.console1 = function() { console.lo ...

Guide on how to validate react-multiselect with the use of Yup validation schema

If the multiselect field is empty, the validation message 'Product is required' is not being displayed. How can I validate this field? Here is the validation schema: validationSchema={ Yup.object().shape({ productID: Yup.string().requi ...

showing images received via a websocket connection

My current setup involves receiving one image per second through a WebSocket connection. The images are in blob format, and I am unsure of the best way to display them. Should I use an image tag or a video player? And how should I go about showing these ...