简体   繁体   中英

add to cart button is not responding

my add to cart button is not responding. I have applied javascript on my add to cart button, In the cart button, I have assigned attribute ie data-product the value that is {{product.id}}.

 var updateBtns = document.getElementsByClassName('update-cart') for (var i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function() { var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'action:', action) }) }
 <div class="card-body"> <h5 class="card-title fw-bold text-uppercase">{{product.name}}</h5> <p class="card-text"> <h4 style="font-size: 1rem; padding: 0.3rem; opacity: 0.8;">$ {{product.price}} </h4> </p> <button data-product={{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">ADD TO CART</button> </div> </div>

The console is not showing anything even though I click on Add to Cart button several times

Instead of getElementsByClassName use querySelectorAll beacuse as @tacoshy stated getElementsByClassName returns an object of HTML Collection not an array. Also length would return the amount of elements within an array but not an object.

const updateBtns = document.querySelectorAll('.update-cart')

updateBtns.forEach((updateBtn) => {
    updateBtn.addEventListener('click', (event) => {
        var productId = updateBtn.dataset.product
        var action = updateBtn.dataset.action

        console.log('productId:', productId, 'action:', action)
    })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM