Home > Software engineering >  Multiple buttons with the same class name but only the first one works
Multiple buttons with the same class name but only the first one works

Time:10-18

I'm fairly new to JS and I currently working on the front-end of a very basic ecommerce page as a personal project.

Here's my question, all the "items" on the page are exact the same aside from their name. When I click on "buy", I'd like to send the name of the respective item to the cart. However every time I click on any buy button, instead of sending the title of the item I just clicked, it always sends the "Item 1".

I've been trying to figure this out for sometime now but no luck so far.

Thanks in advance!

--HTML--

<body>
    <div id="navbar">
        <p id="logo">eCommerce</p>
        <div id="cart">
            <img src="icons/shoppingcart.svg" alt="cart" id="cart-icon">
            <a href="#" id="cart-quantity"></a>
        </div>
    </div>

    <div id="cart-container">
        <div id="cart-content">
            <p id="cart-items">Your cart is empty</p>
        </div>
    </div>

    <div id="items">
        <div >
            <img src="http://mattgreenhalgh.com/wp-content/uploads/2017/02/Placeholder_1080p.png" alt="product-img">
            <div >
                <p >Item 1</p>
                <p >Price: $100</p>
            </div>
            <button >add to cart</button>
        </div>

        <div >
            <img src="http://mattgreenhalgh.com/wp-content/uploads/2017/02/Placeholder_1080p.png" alt="product-img">
            <div >
                <p >Item 2</p>
                <p >Price: $100</p>
            </div>
            <button >add to cart</button>
        </div>

        <div >
            <img src="http://mattgreenhalgh.com/wp-content/uploads/2017/02/Placeholder_1080p.png" alt="product-img">
            <div >
                <p >Item 3</p>
                <p >Price: $100</p>
            </div>
            <button >add to cart</button>
        </div>

        <div >
            <img src="http://mattgreenhalgh.com/wp-content/uploads/2017/02/Placeholder_1080p.png" alt="product-img">
            <div >
                <p >Item 4</p>
                <p >Price: $100</p>
            </div>
            <button >add to cart</button>
        </div>

        <div >
            <img src="http://mattgreenhalgh.com/wp-content/uploads/2017/02/Placeholder_1080p.png" alt="product-img">
            <div >
                <p >Item 5</p>
                <p >Price: $100</p>
            </div>
            <button >add to cart</button>
        </div>

        <div >
            <img src="http://mattgreenhalgh.com/wp-content/uploads/2017/02/Placeholder_1080p.png" alt="product-img">
            <div >
                <p >Item 6</p>
                <p >Price: $100</p>
            </div>
            <button >add to cart</button>
        </div>

        <div >
            <img src="http://mattgreenhalgh.com/wp-content/uploads/2017/02/Placeholder_1080p.png" alt="product-img">
            <div >
                <p >Item 7</p>
                <p >Price: $100</p>
            </div>
            <button >add to cart</button>
        </div>

        <div >
            <img src="http://mattgreenhalgh.com/wp-content/uploads/2017/02/Placeholder_1080p.png" alt="product-img">
            <div >
                <p >Item 8</p>
                <p >Price: $100</p>
            </div>
            <button >add to cart</button>
        </div>
    </div>

    <script src="app.js"></script>
</body>

--JS--

/* global variables */
const itemsForSale = document.querySelector('#items')
const cartQuantity = document.querySelector('#cart-quantity')
const cartContent = document.querySelector('#cart-icon')
const cartItems = document.querySelector('#cart-content');

/* cart array */
const cart = []


/* -------------------------------------------------------- 
functions -------------------------------------------------
----------------------------------------------------------- */


/* add to cart function */
const addToCartBtn = document.querySelector('.addToCartBtn');

addToCartBtn.onclick = function () {

    /* items in cart */
    const itemName = document.querySelector('.product-name').innerHTML;

    cart.push(itemName)
    console.log(cart)

    /* add item name to the cart */
    for(i = 0; i < cart.length; i  ) {
        document.querySelector('#cart-items').textContent = `${cart[i]}`
    }

    /* quantity of items in cart */
    cartSum = cart.length
    cartQuantity.textContent = cartSum

};



/* show/hide item content */
cartContent.addEventListener('click', function() {
    if(cartItems.style.display == 'none') {
        cartItems.style.display = 'flex';
    } else {
        cartItems.style.display = 'none';
    }
});

CodePudding user response:

This is because querySelector returns the first instance of the element in the DOM that corresponds to the class you are looking for. To fix this, first of all, I listened to the event of clicking all the buttons with querySelectorAll, and in the function itself, I searched for .product-name according to the parent closest to the button that has the class product

/* add to cart function */
const addToCartBtn = document.querySelectorAll('.addToCartBtn');

addToCartBtn.forEach(btn => {
    btn.onclick = function (e) {

    /* items in cart */
    const itemName = e.closet('.product').querySelector('.product-name').innerHTML;

    cart.push(itemName)
    console.log(cart)

    /* add item name to the cart */
    for(i = 0; i < cart.length; i  ) {
        document.querySelector('#cart-items').textContent = `${cart[i]}`
    }

    /* quantity of items in cart */
    cartSum = cart.length
    cartQuantity.textContent = cartSum

    };
}

CodePudding user response:

Try this code, simple and do the work perfectly :)

let AddTocartButton = document.querySelectorAll('.addToCartBtn');
let ProductNames = document.querySelectorAll('.product-name');
let cart = document.querySelector('#cart');
AddTocartButton.forEach((element , index) => {
    element.onclick = function () {
        let CartItem = document.createElement('a');
        let itemName = ProductNames[index].textContent;
        CartItem.textContent = itemName;
        cart.appendChild(CartItem);
    }
});
  • Related