Lee J Lee J - 6 months ago 54
jQuery Question

How to use the same function for a button inside a loop?

I have a homepage where it shows products from the database and I placed an add to cart button that of course will add each specific product to the cart. Currently I have 6 products shown on the page but apparently only the first product can be added to the cart and the rest has a button that does not work.

Upon research it is advised that we cannot use the same id multiple times via JavaScript (I am using id="add-to-cart") and that is what's happening inside the loop therefore only the first item has a working button.

How can I generate specific ID's to each add to cart button on my while loop and how will the script recognize or read each specific id? I am no JavaScript expert.

$result = mysqli_query($bd,$sql2);


$prodID = $row["ID"];

$prodname= $row["itemname"];
$prodprice = $row["price"];


<h1 class="product"><?php echo $prodname; ?></h1>
<p>Price: <span class="price"><?php echo $prodprice; ?></span></p>
<a class="btn btn-default add-to-cart cartButtons" id="add-to-cart" input>Add to Cart</a>
<p class="info hidethis" style="color:red;"><strong>Item Added to Cart!</strong></p>

Here's the script:

var price = $(this).siblings('p').children('.price').html();
var product = $(this).siblings('.product').html();

Answer Source

Per your example, remove your id="add-to-cart", then adjust the jquery click like this:

$('.add-to-cart').on('click',function(){ ... });

This will give that click event to all buttons set to be of class add-to-cart. Since you already use $(this) inside your click event function, it is already pulling the details from THAT click, and not others.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download