Is there a way to automatically recalculate the "Total Price" when the input values are adjusted?

Whenever I add an item to the cart, it gets appended to the row in the shopping cart, and the price adjusts accordingly. However, I'm having trouble getting the price to adjust whenever I change the input values (input type: "number"). I can't seem to find the correct format for this. Can someone help me out? Your feedback is greatly appreciated. Here to learn!

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>E-Commerce Website</title>
    <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.css" />
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css" />
    <link rel="stylesheet" href="/fonts/fontawesome-free-5.3.1-web/css/all.css"><link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

    <link rel="stylesheet" href="style.css">
    
</head>
<body>
    <div class="wrapper">
        <div class="p1" id="p1">
            <div class="topnavcont">
                <ul class="topleftnav">
                <a href="#p1"><li class="topnavlink">Home</li></a>
                <a href="#p2"><li class="topnavlink">Shop</li></a>
            </ul>
            <h1 class="topnavtitle">The Store</h1>
            <div class="navcartcontainer">
                <h3 class="totalnumber">0</h3>
                <i class="fas fa-shopping-cart" id="cartbtn"></i>
            </div>
            </div>

            <!-- <img src="clark-street-mercantile-vC-GqGbakJo-unsplash.jpg" alt="" class="bgimg"> -->
            
            <div class="swiper-container">
                <!-- Additional required wrapper -->
                <div class="swiper-wrapper">
                    <!-- Slides -->
                    <div class="swiper-slide"><img src="clark-street-mercantile-P3pI6xzovu0-unsplash.jpg" alt="" class="bgimg"><div class="overlay"></div></div>

                    <div class="swiper-slide"><img src="michela-ampolo-7tDGb3HrITg-unsplash.jpg" alt="" class="bgimg"><div class="overlay"></div></div>

                    <!-- <div class="swiper-slide">Slide 3</div>
                    ... -->
                    </div>
                    <!-- If we need pagination -->
                    <div class="swiper-pagination"></div>
                
                    <!-- If we need navigation buttons -->
                    <div class="swiper-button-prev arrow"></div>
                    <div class="swiper-button-next arrow"></div>
                
                    <!-- If we need scrollbar -->
                    <div class="swiper-scrollbar"></div>
                </div>
            <div class="cartbody">
                <i class="fal fa-times" id="closeicon"></i>
                <h2 class="carttitle">Shopping Cart</h2>
                <ul class="cartitems">
                    
                </ul>
                <h3 class="actualprice carttotal"id="actualprice">Total: $0</h3>
                <button class="purchasebtn" id="purchasebtn">Purchase</button>
                
            </div>
        </div>

<div class="p2" id="p2">
    <h1 class="p2title">My Shop</h1>
    <div class="itemcontainer">
  
</div>
    <script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll/dist/smooth-scroll.polyfills.min.js"></script>
    <script src="https://unpkg.com/swiper/swiper-bundle.js"></script>
<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
    <script src="app.js"async></script>
</body>
</html>

CSS:

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}
::-webkit-scrollbar{
    display: none;
}
.wrapper{
    overflow-x: hidden;
}


/* Rest of the CSS code remains unchanged */

JAVASCRIPT:

    let TotalNumber = document.querySelector(".totalnumber");
    // JS code has been removed for brevity

Answer №1

One issue arises when you adjust the quantity of an item in your shopping cart, as the price is incorrectly recalculated each time.

For example, if you currently have "Red Shoes" in your Cart priced at $4.99,

When you increase the quantity by one, the total is miscalculated and now shows $14.97 (initial $4.99 + 2 multiplied by the unit price).

To resolve this, it's recommended to save the original quantity before making changes and then subtract it from the total before adding more items:

(originalPrice - unitPrice * oldQuantity + unitPrice * newQuantity).toFixed(2);

I hope this explanation clarifies things for you. Have a wonderful day! Feel free to reach out if you require further assistance. (:

Answer №2

Here's the modified portion, with redundant code removed:

function updateAmounts() {
  let total = 0
  document.querySelectorAll(".qinput").forEach(el => {
    let qty = +el.value
    let price = +el.closest('.cartitem').querySelector('.itemprice').innerText.trim().replace('$', '');
    total += (qty * price);
  })
  document.querySelector(".actualprice").innerHTML = `Total: $${total.toFixed(2)}`
}
document.querySelectorAll(".qinput").forEach(el => el.addEventListener("change", (e) => updateAmounts()))

The functionality includes:

  • Updating totals when quantity changes in a .qinput field
  • Calculation of total by iterating through all relevant fields and multiplying the quantity by their respective prices

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

Using jQuery to toggle the visibility of div elements while displaying an indicator

A query arises regarding the utilization of JQuery to facilitate toggling the visibility of text divs. The question pertains to how one can incorporate an indicator - such as an up and down arrow graphic - to denote whether the divs are open or closed. Sug ...

Modify the heading color of elements in a class to a distinct color when the cursor hovers over the element

I currently have 3 heading elements: elem1, elem2, and elem3. When I hover over elem1, I want elem1 to turn yellow and elem2 and elem3 to turn purple. If I hover over elem2, I want elem2 to be yellow and the others to be purple. Once I release the hover, I ...

Do we really need Renderer2 in Angular?

Angular utilizes the Renderer2 class to manipulate our view, acting as a protective shield between Angular and the DOM, making it possible for us to modify elements without directly interacting with the DOM ourselves. ElementRef provides another way to al ...

Angular array mapping techniques

My JSON Object $scope.selectedItems ={ "RECORDS": [ { "Id": 23040035705987, "arriveddate": "2015/04/24", "expirationDate": null, "replacedDate": null, "processDate": "2015/04/24" ...

Achieving an element placement in a navigation bar with flexbox and grid layout | HTML and CSS exclusive techniques

Need help achieving the desired result using only flexbox and grid layout. The goal is to place a search bar vertically centered and to the right of the navbar, while keeping the existing items on the left intact. Can you assist? /* Reset */ * { mar ...

Code error: JSON unexpected token "&" encountered

When utilizing the $http.get() method for a GET request, the response is in JSON format, but some characters are HTML encoded. For example, the double quote " is encoded as &quot;. { &quot;description&quot;:&quot;invalid&quot;, ...

UI Router: Easily navigate to a specific route by entering the URL directly

I encountered what I thought would be a common issue, but my search turned up empty. I have two states - one accessed at /route and the other at /route/{name}. Everything functions properly when I navigate to the second route using ui-sref, however, if I r ...

Do not use the .map method! Caution: Every child component in a list must be assigned a unique "key" prop

I have recently started working with NEXT JS and I am encountering a peculiar issue for which I haven't been able to find a solution online. The warning message I'm getting is: "Each child in a list should have a unique key prop." Warning: Each c ...

The ComponentDidUpdate function treats the previous state (prevState) and the current state (this

Initially, I had a state update function that looked like this: doChangeValue(data) { const dataNew = this.state.data dataNew[data.id] = data.value this.setState({ ...dataNew, [dataNew[data.id]]: data.value}) } However, I realized that thi ...

Unable to utilize Bower due to a node.js malfunction

Currently facing an issue while attempting to utilize bower for installing all necessary components for my website project. Each time I make an attempt, the following error presents itself: TypeError: Object #<Object> has no method 'toLowerCase ...

iterating over a list of files using JavaScript

I am currently working on setting up individual ajax requests for each file being uploaded. I have a functioning ajax call that creates a record, returns some html, and provides the tempID of the record which is then used in another ajax call that triggers ...

What is the method to escape from a for loop in Protractor?

Check out my code snippet: formElements[0].findElements(by.repeater(repeater)).then(function(items){ console.log(i, '>>>>>>>>>.No of items in the list --- '+items.length); (function(items){ ...

The dependencies were not updated after running `npm install`

When attempting to update the dependencies in my react-native CLI app by running npm install for the package.json, I encountered issues. Subsequently, I tried using npm audit fix and npm audit fix --force without success. In an effort to resolve the probl ...

Using mongoose to differentiate whether an update-upsert operation is performing an insert or an update

Is the "upsert" option for updating working correctly? I attempted to upsert an object into mongodb twice with the same key, but did not receive an inserted message. Am I overlooking something? (mongodb : v2.6.3; mongoose : 3.8.15) Member.findOneAndRemov ...

I'm wondering why this isn't working properly and not displaying the closing form tag

What could be the reason for this not functioning properly? The tag appears to close on its own and the closed tag is not being displayed. As a result, the if(isset($_POST['payoneer-btn'])) statement is not triggering. https://i.stack.imgur.com/ ...

Adjust a Javascript script to choose the best font color for use in R Shiny applications

I am currently seeking to determine the font color of hover messages based on the background color. This means white if the background is dark, and black if it is light. However, I stumbled upon a Stack Overflow question with a Javascript solution that see ...

AngularJS: The art of object pushing

I have a small application where I need to read data from a JSON file, display it, and allow users to add records to it. Specifically, I have an array called condition within the patient object, and I want to insert a new item into this array based on user ...

Encounter Issue: "Describe" function not recognized. This error occurred during the activation of Mocha Test

https://i.sstatic.net/WBSm6.png Upon my installation of mocha, I encountered an issue while running a test using a command, resulting in the error message "describe is not a function." ...

How do I activate the <li> tag using jQuery?

I am currently implementing pagination on my webpage using the following JavaScript code: var pagingList = $('<ul>', {class: 'pagination list-unstyled list-inline'}); ...

Combining Strings and Integers in Javascript

Currently, I am facing a frustrating syntax issue with my code. I am using Scissors, a Node Module for managing pdf files. The documentation describes the syntax for selecting specific pages of the Pdf: var scissors = require('scissors'); var p ...