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

Challenges with Dual Y-Axis in a Horizontal Stacked Bar Graph

My charts are presenting me with several issues and questions: Is there a way to avoid the right y-axis tick values from either being partially erased or overlapping with the chart? When I set yValuesTripId as the domain for both the left and right y ...

Initiate the month transition event within the fomantic calendar

In my project, I have integrated the fomantic calendar and it is working properly. However, I am facing an issue when it comes to changing the month. Is there a specific event for month changes in the fomantic calendar? I am struggling to make it work. Tha ...

"Utilizing social links in web design for a seamless user experience

I'm currently exploring ways to repair the design of social media links. The GitHub and Spotify icons are displaying at different sizes, and it seems like the Blogger icon is not aligning correctly: Referring to How To Create Social Media Buttons - ...

splitting xmlhttp.responsetext using loops

Currently, I have a JavaScript function that utilizes xmlhttp.responsetext to fetch data from MySQL. This data is then used to populate form fields in a dropdown menu, which has been functioning perfectly so far. However, the issue arises when I attempt to ...

Can someone show me how to verify in PHP (using codeigniter) if the following two rows contain any data?

I need to verify whether the following TWO rows or ID are not NULL. If there are no consecutive TWO rows or ID, then the income will stay at zero. foreach ($data as $row) { if(($row->id + 2) != NULL) //I am unsure about the c ...

Angular Bootstrap UI - Ensuring only one element collapses at a time

I have integrated the angular bootstrap UI library into my website by following this link: https://angular-ui.github.io/bootstrap/ One issue I am facing is that when I implement a collapsible feature using this library, it collapses or expands every eleme ...

Expanding the size of an array list item in React

I have an array containing various currencies: const currencies =['USD','EUR','AUD','CNY','AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'A ...

Difficulty with Vue.js updating chart JS label names

I have been working with Vue JS and implementing a chart in my single page application. However, I am encountering difficulties updating the Legend and despite numerous attempts and searches, I am unable to get it to update. Any assistance in correcting my ...

How to perfectly align content on a webpage

Can someone help me understand why my webpage is off-centered as it scales up? I have set a minimum width of 1000px, but it still appears to be centered at 30%-70%. Any insights on this issue would be greatly appreciated. <!DOCTYPE html PUBLIC "-//W3 ...

Trigger an input file click automatically using vanilla JavaScript with an AJAX request in Google Chrome

Currently, my webapp operates in a way that every button click triggers an ajax request to the server. The server then validates and sends JavaScript code back to the client. Unfortunately, the framework I am using does not allow me to incorporate jQuery a ...

Error encountered when attempting to establish a connection between socket.io and express: network error

Similar Question: socket.io: Failed to load resource I'm having trouble getting a simple express + socket.io hello world app to work. I keep receiving the following error: "NetworkError: 404 Not Found - http:// localhost:3002/socket.io/socke ...

Raycast in Three.js is struggling to locate object

Whenever I select a 3D model, my goal is to retrieve the object's ID, name, or the actual object itself in order to effectively delete it. function onDocumentMouseDown( event ) { if (enableRaycasting){ event.preventDefault(); mouse.set( ( event.c ...

Content Security Policy in Firefox Extension blocking local DataTables js

After downloading the js for DataTables, I attempted to load it onto my Firefox extension but encountered a Content Security Policy block: Content Security Policy: The page’s settings blocked the loading of a resource at self (“default-src moz-ext ...

Step by step guide on incorporating two background images in a single header

I'm looking to create a header with a background image that appears twice, like this: To achieve the effect, I added opacity of 0.5 to one of the images, but it is affecting everything in my header including text and logo. Is there a way to prevent t ...

Prevent floating labels from reverting to their initial position

Issue with Form Labels I am currently in the process of creating a login form that utilizes labels as placeholders. The reason for this choice is because the labels will need to be translated and our JavaScript cannot target the placeholder text or our de ...

Broken styles when using Material UI with babel and the 'with styles' feature

We've implemented babel and lerna to maintain specific elements of our react web app separately. While the setup has been effective thus far, we're encountering styling issues when generating the static build. The main project is not processed t ...

Tips for concealing the bar graph while maintaining the visibility of the data labels in HighCharts

Is there a way to hide one bar but keep the data labels in HighCharts? I have 3 bars: Target Realization Percentage I want to display only the first and second bars, with only 1 data label which is the percentage. So, I made some adjustments to my co ...

Troubleshoot my code for clustering markers on a Google map

I'm currently working on a piece of code to generate a Google map that contains 3 hidden points within one marker. The idea is that when the main marker is clicked, these points will either merge into one or expand into 3 separate markers. However, I& ...

Issue "cannot update headers after they have been sent"

I've been working on a node.js application to retrieve movie listings using the omdb api. However, I'm encountering an error when attempting to access the /result route. The error message is as follows: Error: Can't set headers after they ar ...

Event handler for the MouseLeave event is not successfully triggering when dealing with anchor

When viewing a link to a Codepen, the issue is most noticeable in Chrome: https://codepen.io/pkroupoderov/pen/jdRowv Sometimes, the mouseLeave event fails to trigger when a user quickly moves the cursor over multiple images, resulting in some images reta ...