So, I’m trying to make a plus or minus quantity button for the items that are in my cart in an e-commerce website. What I want to do is be able to, for every separate item, be able to modify the quantity in the cart.
I tried running this code and I expected it to allow me to change, for every different item, the quantity for every single item, except what actually happens is that even if I click the plus or minus buttons in the second, third item in the cart, it changes the quantity of the first item. How can I change this?
I tried putting
item.forEach(function(element){
element.quantityInput.value = currentValue + 1;
})
but it doesn’t work.
<body>
<h1>Your Cart</h1>
<div class="cart-container" id="cart-container">
<div class="cart">
<?php while ($row = $result->fetch_assoc()): ?>
<div class="cart-item" id="cart-item">
<h2><?php echo $row['productname']; ?></h2>
<img id="img" style="border-radius:20px;width:150px" src="data:image/jpg;charset=utf;base64, <?php echo base64_encode($row["productimage"]); ?>"/>
<p>Price: $<?php echo $row['price']; ?></p>
<p>Quantity: <?php echo $row['quantity']; ?></p>
<p>Subtotal: $<?php echo $row['price'] * $row['quantity']; ?></p>
<div class="quantity-selector">
<button class="minus-btn" onclick="decrement()">-</button>
<input type="number" id="quantity" value="1" min="1">
<button class="plus-btn" onclick="increment()">+</button>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
<script>
var item= document.getElementById("cart-item")
function increment() {
var quantityInput = document.getElementById('quantity');
var currentValue = parseInt(quantityInput.value);
quantityInput.value = currentValue + 1;
}
function decrement() {
var quantityInput = document.getElementById('quantity');
var currentValue = parseInt(quantityInput.value);
if (currentValue > 1) {
quantityInput.value = currentValue - 1;
}
}
</script>
Luzzi98 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.