Is there a way to adjust the quantity individually, both increasing and decreasing as needed?

I am currently working on implementing a shopping cart feature using pure JS that allows users to increase and decrease the quantity of items. When the + or - button is clicked, both items in the shopping cart will be affected simultaneously if there are 2 items present.

Below is the code I have been working on:

function loadCart() {
    let products = JSON.parse(localStorage.getItem('products'));
    let cartTotalItem = document.querySelector('.cart__value');
    cartTotalItem.textContent = products.length;
    products.forEach(product => {
        let cartItem = document.createElement('tr');
        cartItem.innerHTML = `<td><img src="${product.imgSrc}" alt='product image'></td>
                  <td>${product.name}</td>
                  <td><span class='cart-price'>${product.price},000vnd</span></td>
                  <td>
                    <button data-action="remove" onclick='decrease()'>-</button>
                    <input name='product' class="product__quantity" type="number" min='1' max='100' value='${product.count}'>
                    <button data-action="add" onclick='increase()'>+</button>
                  </td>
                  <td><span class='cart-total-value'>${parseInt(product.price) * product.count},000vnd</span></td>
                  <td>
                    <button class="delete--item"><i class="far fa-trash-alt"></i></button>
                  </td>`;
        tableBody.appendChild(cartItem);
    });
}

function increase() {
    let products = JSON.parse(localStorage.getItem('products'));
    for (let i = 0; i < products.length; i++) {
        let inputValue = document.querySelector('.product__quantity').value;
        inputValue = products[i].count++;
    }
    localStorage.setItem('products', JSON.stringify(products));
    tableBody.innerHTML = '';
    loadCart();
}

function decrease() {
    let products = JSON.parse(localStorage.getItem('products'));
    for (let i = 0; i < products.length; i++) {
        let inputValue = document.querySelector('.product__quantity').value;
        inputValue = products[i].count--;
        if (products[i].count <= 0) {
            const itemIndex = products.findIndex(product => product.count === 0);
            products.splice(itemIndex, 1);
        }
    }
    localStorage.setItem('products', JSON.stringify(products));
    tableBody.innerHTML = '';
    loadCart();
}

If anyone could offer some assistance, it would be greatly appreciated.

Answer №1

The problem lies within your for loop. Iterating through the products array, you then increment the count of each product.

newCount = products[i].count++;

To remedy this issue, only update the count of the specific product chosen by passing a product identifier to your increase and decrease functions.

While there may be additional flaws in the code, addressing the above should provide clarity on your inquiry.

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

Fetching data using ajax and then appending it to the webpage

I am currently loading content from a PHP file in JSON format. products.php <?php $stmt = $mysqli->prepare("SELECT * FROM products LIMIT 10"); $stmt->execute(); $products = $stmt->get_result(); $produc ...

When utilizing an API to render text into a div, the offsetHeight function may return 0

I'm working with a div that displays text fetched from an API call. I'm trying to implement a See more button if the text exceeds 3 lines. Here is my approach: seeMore(){ this.setState({ seeMore: !this.state.seeMo ...

Using jQuery to handle nested div elements and triggering a click event only once when the inner div is clicked

I have a situation where I have nested divs. When the inner div (closeme) is clicked, I do not want the click event of the outer div (container) to be triggered. How can I achieve this? html <div id="container"> content <div id="closeme">< ...

Struggling to implement OAuth2 authentication in PHP for the MapMyFitness API

Hello everyone, I am currently exploring the use of MapMyFitness' API and OAuth2 for a project. Below is the simplified code snippet I have implemented, similar to what I've successfully used with Strava's and RunKeeper's APIs: $mapM ...

Meteor: Transmitting Session data from the client to the server

Below is the code snippet I am utilizing on the client side to establish the Session variable: Template.download.events({ 'click button': function() { var clientid=Random.id(); UserSession.set("songsearcher", clientid); ...

Using an Angular route to trigger the resolution of data from a service

I'm having trouble figuring out how to implement Angular route resolve. The documentation does not provide much help for more complex aspects of the javascript framework like this. Here is the service I am using: app.service("AuthService", ["$http", ...

What is the most effective way to loop through HTML elements using wildcards in Puppeteer to extract innerText?

Seeking insights for educational purposes, I am in search of the reviews on this specific page . Each page contains 10 reviews, and I have a set of HTML selectors (previously used code) to extract these comments: #review_593124597 > div:nth-child(1) &g ...

Get access to the file upload field using ajax

I'm encountering an issue with accessing the file upload field //HTML <input type='file' name='images' id="images" multiple> ////////////////// $('.bt-add-com').click(function(){ var formdata = new For ...

Having trouble with my bootstrap slider carousel - it's just not cooperating

I incorporated Bootstrap's carousel to display the various courses on my website, featuring three courses at a time before transitioning to the next set of three. However, I am encountering an issue with this setup. Please see the image below for refe ...

Extracting data from a JSONArray without a specified key using restassured

While utilizing RestAssured for testing my REST APIs, I encountered a scenario in which the API returns a JSONArray without any key-value pairs as shown below. Is it possible to verify such JSON structures using RestAssured? [ "Test_1 Bundle_01", ...

Exploring JSON File data and showcasing it with Python

There is a JSON data source at 'https://api.exchangerate.host/symbols' that contains information in the format 'symbols': {'AED': {'code': 'AED', 'description': 'United Arab Emirates Dirham& ...

Unraveling deeply nested array objects in JSON with Java Script/jQuery

I need help working with a JSON file that looks like the following: {[ {"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}, {"Folder":[ {"name":"John"}, {"name":"Anna"}, {"Folder":[ {"name":"gg"}, ...

Are there any AJAX tools or packages in Node.js Express for connecting (posting/getting) with other servers and retrieving data?

Can someone please guide me on how to utilize ajax in node.js to send and receive JSON data from another server? Is there a package available that allows for this functionality, similar to jQuery's $.ajax, $.post, or $.get methods? ...

A guide on effectively parsing a JSON Array in an Android application

I am struggling to retrieve the name, email, and image for each TAG to display in a list element. { "response":[ { "name":"Brajendra Mishra", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d ...

Guide on saving a Facebook image to a web server directory with Node.js and Express

Looking for some help here - I'm trying to download and save images from a user's Facebook album onto my server folder. My server is running on node.js and express, but when I tried using http.get it didn't work. Any advice or solutions wou ...

Is there a way to preserve EXIF data when converting an image to base64?

I am currently facing an issue with reading a local image that has been created with a different exif.Orientation based on the degree of rotation. const exifData = piexif.load(data.toString("binary")); // Assign the desired orientation value ...

Differences between async/await and then methods in React, demonstration shows that only async/await is functional. Why is

Trying to understand and implement two different API data fetching methods in React app development. The first method involves using the JavaScript Fetch API, while the second method utilizes the async/await syntax. I am currently experimenting with both a ...

Steps to extract key and value from a collection in Firebase database

In my Firebase database, I have a specific structure that I need to retrieve and display using ngFor in my view. However, I also need access to the unique key generated by Firebase when using the push method for each object. https://i.sstatic.net/nR2nK.pn ...

What is the best way to eliminate the nesting in this ternary operation?

Object.values(filter).filter(item => (Array.isArray(item) && item.length > 0) || (typeof item === "boolean" && item === true) || (item !== null)).length ? filterIcon : unFilledIcon In this code, I aim to simplify the nested ternary operator and ...

Refrain from revealing AngularJS code before activating it

My AngularJS code displays every time I reload the page https://i.sstatic.net/bzYrr.png Issue: The code appears even when my internet connection is slow or the page does not fully reload. I only want it to display the result. I would appreciate any sugg ...