0

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.

zohaib_webdev
  • 33
  • 1
  • 8
  • `this` is pointing to the global (window) object and not your button. You either need to use a normal function or replace `this` with `updateBtns[i]`. [More info about this keyword here](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Reyno May 31 '21 at 10:10

2 Answers2

0

Try something like this

for(var i=0; i<updateBtns.length; i++){
      updateBtns[i].addEventListener('click', (event)=> {
      var action = event.target.dataset.action;
       var productId = event.target.dataset.product;
        })  
     }
Jake C
  • 136
  • 5
0

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;
  });
}
cfarhad
  • 168
  • 10