I have a problem with using javascript with SQL.
It looks like this that I have few items that appears on the screen, they appears from SQL database, and the code looks like shown. Bascially if I have more than one product that is shown on the website, only first one works as it should. Any solutions?
let displayAddCounter = document.querySelector("#add_count_cart");
let displayRemoveCounter = document.querySelector("#remove_count_cart");
let displayCounter = document.querySelector("#amount_count_cart");
var x = 0;
displayAddCounter.addEventListener("click", function(){
if(x < 10){
x++;
displayCounter.innerHTML = x;
} else {
alert("If you want to buy more than 10, please contact our support! We will gladly help you :)")
}
});
displayRemoveCounter.addEventListener("click", function(){
if(x == 0){
displayCounter.innerHTML = x;
} else {
x--;
displayCounter.innerHTML = x;
}
});
let buttonCartAdd = document.getElementById("btn_add_to_cart");
let itemName = document.querySelector(".product_name");
buttonCartAdd.addEventListener("click", function(){
if(x == 0){
alert("Please choose amount of items!");
}
else if(x > 0){
alert("You added " + x + itemName.innerHTML + " to the cart!");
}
});
<?php
$sql = "SELECT * FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<div class="product_card col-lg-4 col-md-6 col-sm-12 mb-4 box-shadow">
<div class="card-header">
<h3 class="product_name my-0 font-weight-light"> <?php echo $row["productName"]?> </h3>
</div>
<div class="card-body">
<h2 class="card-title pricing-card-title"> </h2>
<img class="pic" src="productsImages<?php echo $row["productID"];?>.jpeg" height="150px" width="120px"></img>
<br>
<p>
<?php echo $row["productPrice"];?> SEK
</p>
<div class="row amount_counter">
<button id="remove_count_cart" type="button" class="col_amount btn btn-outline-secondary col-3 col"> - </button>
<div id="amount_count_cart" class="btn col-6 col border-top border-bottom dark rounded h-75">
0
</div>
<button id="add_count_cart" type="button" class="col_amount btn btn-outline-secondary col-3 col"> + </button>
<button id="btn_add_to_cart" class="btn btn-lg btn-outline-success col-lg-8 col-md-12 col offset-lg-2"> Add <i type="button" class="fas fa-cart-plus"></i></button>
</div>
</div>
</div>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>