Count item in cart

I need js code to count item quantity in every cart row. can someone help me.

let removeCartItemButtons = document.querySelectorAll('.delete-cart');
        for (let i = 0; i < removeCartItemButtons.length; i++) {

            let button = removeCartItemButtons[i]
            button.addEventListener('click', removeCartItem)
        }

        let quantityInputs = document.querySelectorAll('.quantity-input');
        for (let i = 0; i < quantityInputs.length; i++) {

            let input = quantityInputs[i]
            input.addEventListener('change', quantityChanged);
        }

        function removeCartItem(event) {
            let buttonCliked = event.target;
            buttonCliked.parentElement.parentElement.remove()
            updateCartTotal()
        }

        function quantityChanged() {

            let input = event.target;
            if (isNaN(input.value) || input.value <= 0) {
                input.value = 1;
            }
            updateCartTotal()
        }

        function updateCartTotal() {
            let cartItemContainer = document.querySelector('.click-cart');
            let cartRows = cartItemContainer.querySelectorAll('.cart-row');

            let total = 0
            for (let i = 0; i < cartRows.length; i++) {
                let cartRow = cartRows[i]
                let priceElement = cartRow.querySelector('.shop-price');
                let quantityElement = cartRow.querySelector('.quantity-input');

                let price = parseFloat(priceElement.innerText.replace('$', ''))
                let quantity = quantityElement.value
                total = total + (price * quantity)
            }
            total = Math.round(total * 100) / 100
            document.querySelector('.cart-total-price').innerText = '$' + total;
        }

My first advice would be not to use the DOM for the state. Create state data structures, for example, an array of objects (cart items, products, users, whatever) update the state (add, remove, filter) then render its content to the DOM. Let the DOM reflect the state, but not be the state.

In that case, all you need to get the total number of cart items is to make it an array of objects (cart items) and just use the length property on the array. Anytime you remove or add a cart item object the array length property is adjusted and you only have to update the “view” of the state (i.e. re-render the state).

Any good todo list tutorial will show this way of working.


As for the code you posted, I would suggest you provide the HTML as well so we can test it. Or better yet, post a link to a live version on something like Codepen.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.