I am trying to write an add to cart functionality using Javascript and django (main functionality is Javascript).
I have written this code for the cart.js
var updateBtns = document.getElementsByClassName('update-cart')
console.log("Working");
for (i = 0; i < updateBtns.length; i ) {
updateBtns[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
console.log('productId is:', productId, 'Action is:', action)
console.log('USER:', user)
})
}
And this is the code for template index.html
{% for product in products %}
{{ product.title }}
{{ product.price}}
<button data-product="{{product.id}}" data-action="add" >Add to Cart</button>
{% endfor %}
When i print(product.id)
it gets the specific product id but the button does not wwork
what could be the problem with my code?
CodePudding user response:
Did you actually call that action?
for (i = 0; i < updateBtns.length; i ) {
updateBtns[i].addEventListener('click', function(){
var productId = this.dataset.product
var action = this.dataset.action
// I think that you need to call the action
window[action](productId);
console.log('productId is:', productId, 'Action is:', action)
console.log('USER:', user)
})
}