The "Overall Quantity" of items will vary as it goes through different numerical values, despite the fact that I employed --

I am currently working on an e-commerce website with a shopping cart feature. The cart displays the number of items added to it, which increases by one when 'Add to Cart' is clicked and decreases by one when 'Remove' is clicked. However, I have encountered a bug where each 'Remove' button subtracts different amounts from the total number, rather than just one as intended.

CODE:

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="/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">
    <script src="app.js" async></script>
</head>
<body>
    (...)
</body>
</html>

CSS:

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}
(All CSS styling properties and classes)

JAVSCRIPT:

let TotalNumber = document.querySelector('.totalnumber');
const Atc = document.getElementsByClassName('atcbtn');
const cartbtn = document.getElementById('cartbtn')
const closeicon = document.getElementById('closeicon')
(...)

Answer №1

I see a mistake in the way you've set up your code for removing items - there's no need to call a separate function when you can simply loop through the items directly. The issue here lies in trying to perform mathematical operations on string data, such as with the innerText. To resolve this, just add a + in front of it to convert the value to a number.

for (i = 0; i < removebtn.length; i++) {
    let rbutton = removebtn[i];
    rbutton.addEventListener("click", function() {
        let TotalNumbervalue = +TotalNumber.innerText.trim()
        if (TotalNumbervalue > 0) {
            TotalNumber.innerText--
        }
        rbutton.parentElement.parentElement.remove()
    })
}

Answer №2

removeItem() function iterates over all remove button elements and attaches a click event listener that removes the parent element. Repeatedly calling this function when adding a new item can result in multiple click listeners accumulating, causing them to erroneously remove one instance at a time.

To prevent this issue, it's recommended to add the click event listener after appending the element, ensuring that only one click listener is active at any given moment.

let TotalNumber = document.querySelector('.totalnumber');
const Atc = document.getElementsByClassName('atcbtn');
const cartbtn = document.getElementById('cartbtn')
const closeicon = document.getElementById('closeicon')
const cartbody = document.querySelector('.cartbody')
const removebtn = document.getElementsByClassName('removebtn')
const carttotal = document.querySelector('.carttotal')

cartbtn.addEventListener('click', function() {
    cartbody.classList.toggle('cartbodyactive')
})

closeicon.addEventListener('click', function() {
    cartbody.classList.remove('cartbodyactive')
})


function InputToDefault() {

    let qinput = document.getElementsByClassName('qinput')
    for (let i = 0; i < qinput.length; i++) {
        qinput[i].value = 1;
    }
}

InputToDefault()

function AddItemtoCart() {
    for (i = 0; i < Atc.length; i++) {

        let button = Atc[i];
        button.addEventListener("click", function() {
            let TotalNumbervalue = TotalNumber.innerHTML
            if (TotalNumbervalue > -1) {

                TotalNumber.innerHTML++
            }


            let price = document.getElementById('actualprice')
            let pricenum = price.innerText
            console.log(pricenum)




            let shopitem = button.parentElement
            let shoptitle = shopitem.getElementsByClassName('item-title')[0].innerText
            let shopprice = shopitem.getElementsByClassName('itemprice')[0].innerText
            let cartrow = document.createElement('div')
            let cartitems = document.getElementsByClassName('cartitems')[0]
            let cartrowcontent = `<li class="cartitem"><span class="itemtitle">${shoptitle}</span><span class="itemprice">${shopprice}</span><input type="number" class="qinput"id="qinput"><button class="removebtn">Remove</button></li>`
            cartrow.innerHTML = cartrowcontent;
            cartitems.append(cartrow)
            cartitems.lastChild.querySelector('.removebtn').addEventListener("click", function() {
                let TotalNumbervalue = +TotalNumber.innerText;
                console.log(TotalNumbervalue);
                if (TotalNumbervalue > 0) {
                    TotalNumber.innerText--
                }
                this.parentElement.parentElement

              </div>remove()
            })

            qinput.value = 1
            InputToDefault()
        })
    }
}


AddItemtoCart()
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

::-webkit-scrollbar {
  display: none;
}

.wrapper {
  overflow-x: hidden;
}

.topnavcont {
  padding: 1em 0em;
  align-items: center;
  height: 10vh;
  width: 100vw;
  display: flex;
  justify-content: space-around;
  background-color: white;
  box-shadow: rgba(0, 0, 0, 0.10) 0px 3px 6px, rgba(0, 0, 0, 0.20) 0px 3px 6px;
  position: fixed;
  z-index: 5;
}

.topleftnav {
  display: flex;
  justify-content: space-between;
  width: 10%;
  margin-left: -3%;
  font-weight: bold;
}

.topleftnav li {
  cursor: pointer;
  list-style: none;
  font-size: 1.05rem;
  transition: 0.3s ease;
  border-bottom: transparent solid 2px;
}

.topleftnav li:hover {
  border-bottom: black solid 2px;
  transform: scale(1.1);
}

.topnavtitle {
  margin-right: 2.5%;
}

.navcartcontainer {
  display: flex;
  margin-right: -1%;
}

.topnavcont .totalnumber {
  color: black;
  padding: 0.2em 0.4em;
  border-radius: 50%;
  font-size: 1.25rem;
  height: fit-content;
  /* cursor: pointer; */
  font-weight: bold;
}

.topnavcont i {
  font-size: 2rem;
  margin-left: 0.3em;
  cursor: pointer;
  transition: 0.4s ease;
}

.topnavcont i:hover {
  transform: scale(1.15);
}
...
And so on...

<!DOCTYPE html>
<html lang="en">

...rest of the content remains unchanged...

</body>

</html>

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

Creating an expandable discussion area (part II)

After checking out this query that was posted earlier, I am interested in implementing a similar feature using AJAX to load the comment box without having to refresh the entire page. My platform of choice is Google App Engine with Python as the primary lan ...

Exploring the process of assigning responses to questions within my software program

I am looking to display my question choices as radio buttons in a modal window. I have tried several solutions without success. Here is my question module: import questions from "./Data"; const QuestionModel = () => { return ( <div cl ...

Comparison between SSD and HDD animation speed in web hosting environments

I am currently in search of a web hosting provider for a website I have created. The site features some performance-heavy animations, particularly due to a fullscreen slider with filter and scaling transitions. I need a provider that can ensure optimal per ...

Is Moment.js displaying time incorrectly?

When using moment.tz to convert a specific date and time to UTC while considering the Europe/London timezone, there seems to be an issue. For example: moment.tz('2017-03-26T01:00:00', 'Europe/London').utc().format('YYYY-MM-DD[T]HH: ...

What steps can I take to ensure that this input is neat and tidy

I need to implement conditional styling for my input field. The current layout is chaotic and I want to improve it. Specifically, when the active item is "Height", I only want to display the height value and be able to change it using setHeight. const [a ...

Adding Bootstrap component via ajax request

I'm facing an issue with injecting a Bootstrap component using ajax. I usually include a select element like this: <select class="selectpicker" data-width="75%"> Most of the HTML code is generated dynamically through javascript, which you can ...

Achieving success was like uncovering a hidden treasure chest after a successful

Is there a way to address this JSON data issue? success{"data": [{"id":"1","name":"something1"},{"id":"2","name":"something2"},{"id":"3","name":"something3"}] } The success variable contains the JSON data. This is how the server script returns the data: ...

It seems that BeautifulSoup and Selenium are unable to locate the div or text elements on the website

I have been attempting to utilize BeautifulSoup or Selenium in order to retrieve the Head to Head text or its corresponding div element on betexplorer (link provided below), but my efforts have unfortunately proved to be unsuccessful. Despite being able to ...

Add items to a fresh record using Mongoose and Express

In my model, I have an array of objects that I want to populate with new items when creating a NEW document. While I have found information on how to achieve this using findAndUpdate, I am struggling to figure out how to do it with the save() method. This ...

What is the difference between TypeScript's import/as and import/require syntax?

In my coding project involving TypeScript and Express/Node.js, I've come across different import syntax options. The TypeScript Handbook suggests using import express = require('express');, while the typescript.d.ts file shows import * as ex ...

Transitioning the style code from inline to the head of the document disrupts the straightforward JavaScript intended to

As I delve into the world of web development, I encountered a simple issue that has been causing me frustration for the past hour. It involves code to display the border color of a div element using an alert. The code works perfectly fine when the style is ...

Adjust the size of the div menu according to the window's dimensions

Is there a way to make a menu that will resize both the width and height of the window? I've managed to resize the width using %, but for some reason, the height isn't cooperating. I've experimented with max-width/height settings and tried ...

What is the best method for extracting a particular value from my dataset?

I'm interested in creating a variable that stores the IsUserSiteOwner value from the data. Can someone help me with this? Any suggestions on how I can achieve this task? ...

Timeout for jQuery animations

My jQuery animation script is causing an issue where it does not finish the animation before returning to the parent function. Specifically, the JavaScript code changes a background color, calls the animate function, the animation starts but doesn't c ...

Issue with retrieving body class in Internet Explorer on Magento platform. The body class is not being recognized in IE, but works fine in Mozilla and Chrome

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->getLang() ?>" lang="<?php echo $this->getLang() ?>" dir="ltr"> <?php echo $this->getChildHtml('head') ?> <bod ...

What is the best way to combine the elements within an array with the elements outside of the array in order to calculate their sum?

The goal is to create a function that determines the winner using two input integers. The function should return the first input if it is greater than the second input. function determineWinner(a, b) { let result = [] for (let i = 0; i < 3; i++) ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

I have always wondered about the meaning of " + i + " in Javascript. Can you explain it to

<script> var x,xmlhttp,xmlDoc xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", "cd_catalog.xml", false); xmlhttp.send(); xmlDoc = xmlhttp.responseXML; x = xmlDoc.getElementsByTagName("CD"); table="<tr><th>Artist</th><th>Ti ...

What would be the ideal alternative if the Google Ajax API is unavailable, given that Google does not allow for local installation?

On my website, I include the following script: ... <script type="text/javascript" src="https://www.google.com/jsapi"></script> ... This particular script is from Google and is used to dynamically load other resources, such as the Google Chart ...

Tips for applying a custom design to your MUI V5 styled component

How do I customize the style of a button component in MUI V5? I've been trying to combine old methods with the new version, but it's not working as expected. import { Button } from "@mui/material"; import { styled } from "@mui/mate ...