0

I want to assign an event listener for every button in every container, but I don't want to loop through the buttons first, because Firstly

I want to access the container to use hidden inputs to be passed as parameter to every event listener.

but this way the parameters of every button function will be over written. In the end they all have the same parameter ( parameter of last item in the list).

const products = document.querySelectorAll('.productsContainer');

for (var i = 0; i < products.length; i++) {
  var id = products[i].getElementsByClassName('pr_id')[0].value;
  var price = products[i].getElementsByClassName('pr_price')[0].value;
  var Pname = products[i].getElementsByClassName('pr_name')[0].value
  var btn = products[i].getElementsByTagName('button')[0];
  btn.addEventListener('click', function() {
    openpopUp(id, price, Pname)
  })
}
<div>
  <div class="productCard">
    <img src="'.$row['Picture'].'">
    <h3><a href="productDetails.php?id='.$row['Product_ID'].'">'.$row['Name'].'</a></h3>
    <h4>'.$row['price'].'</h4>
    <Button type="button" class="open">aa</Button>
    <input type="hidden" class="pr_id" id="producId" value="'.$row['Product_ID'].'">
    <input type="hidden" class="pr_name" name="productName" value="'.$row['Name'].'">
    <input type="hidden" class="pr_price" name="productPrice" value="'.$row['price'].'">
  </div>
</div>
Ahmeed00
  • 3
  • 3
  • can you explain what `products` actually is? Or include its initialization – prosach Jan 18 '23 at 17:24
  • @prosach i added it in the first part of the code – Ahmeed00 Jan 18 '23 at 17:24
  • use `const` instead of `var` – Sysix Jan 18 '23 at 17:25
  • EITHER you have a mistake and you only have ONE productsContainer, then change my code to `document.querySelector('.productsContainer').addEventListener` OR you have many, then wrap them in a div with id mainContainer and use my code above as it is written – mplungjan Jan 18 '23 at 17:28
  • @mplungjan i changed var to const and it worked – Ahmeed00 Jan 18 '23 at 17:30
  • this is better: `document.getElementById('mainContainer').addEventListener('click' (e) => { const tgt = e.target; if (tgt.matches('button.open')) openpopUp(parent.querySelector('.pr_id').value, +parent.querySelector('.pr_price').value, parent.querySelector('.pr_name').value) })` – mplungjan Jan 18 '23 at 17:32
  • 1
    @mplungjan thats a very good code, thank u – Ahmeed00 Jan 18 '23 at 17:52

0 Answers0