i have set data in the html elements like
<button data-product={{ product.id }} data-action="add" class="btn btn-outline-primary add-btn update-cart">Add to Cart</button>
and try to access them into the js file like:
var updateBtns = document.getElementsByClassName('update-cart'); for(var i=0; i<updateBtns.length; i++){ updateBtns[i].addEventListener('click', ()=> { var action = this.dataset.action; var productId = this.dataset.product; }) }
but I got error that says cart.js:5 Uncaught TypeError: Cannot read property ‘action’ of undefined at HTMLButtonElement.
Advertisement
Answer
If you use this word, you should not use the arrow function!
for (var i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var action = this.dataset.action; var productId = this.dataset.product; }); }