i have set data in the html elements like
JavaScript
x
2
1
<button data-product={{ product.id }} data-action="add" class="btn btn-outline-primary add-btn update-cart">Add to Cart</button>
2
and try to access them into the js file like:
JavaScript
1
9
1
var updateBtns = document.getElementsByClassName('update-cart');
2
3
for(var i=0; i<updateBtns.length; i++){
4
updateBtns[i].addEventListener('click', ()=> {
5
var action = this.dataset.action;
6
var productId = this.dataset.product;
7
})
8
}
9
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!
JavaScript
1
7
1
for (var i = 0; i < updateBtns.length; i++) {
2
updateBtns[i].addEventListener('click', function(){
3
var action = this.dataset.action;
4
var productId = this.dataset.product;
5
});
6
}
7