Reputation: 21
I am trying to get my jQuery code to increase/decrease the quantity and compute the total price for each item. The problem is, when i press the quantity increase/decrease button for a single item, all quantity fields, for all items in the cart updated to the same value. total price is only given for the first item.
$(document).ready(function() {
$(".item").on("input", ".quantity", function() {
var price = +$(".price").data("price");
var quantity = +$(this).val();
$("#total").text("$" + price * quantity);
})
var $buttonPlus = $('.btn-plus');
var $buttonMin = $('.btn-minus');
var $quantity = $('.quantity');
/*For plus and minus buttons*/
$buttonPlus.click(function() {
$quantity.val(Math.min(parseInt($quantity.val()) + 1, 999)).trigger('input');
});
$buttonMin.click(function() {
$quantity.val(Math.max(parseInt($quantity.val()) - 1, 1)).trigger('input');
});
});
<?php
function shoppingcartelement($productimg,$productname,$price,$productid){
$element="
<form action=\"cart.php?action=remove&id=$productid\" method=\"post\" class=\"cart-items\">
<div class=\"item border rounded\">
<div class=\"row\">
<div class=\"col-md-3\">
<img src=\"$productimg\" alt=\"img1\" class=\"img-fluid\">
</div>
<div class=\"col-md-2 bg-white\">
<h5 class=\"pt-2\">$productname</h5>
<p id=\"$productid\"></p>
<h5 class=\"price pt-2\" data-price=\"$price\">$ $price</h5>
</div>
<div class=\"col-md-3 py-5 bg-white\">
<div class=\"input-group\">
<span class=\"input-group-btn\">
<button type=\"button\" class=\"btn btn-info btn-minus\" data-type=\"minus\" data-field=\"quant[1]\">
<img style=\"height:15px\" width=\"15px\" src=\"./icon/minus.png\" alt=\"\">
</button>
</span>
<input type=\"text\" class=\"quantity form-control mx-1\" value=\"1\">
<span class=\"input-group-btn\">
<button type=\"button\" class=\"btn btn-info btn-plus\" data-type=\"plus\" data-field=\"quant[1]\">
<img style=\"height:15px\" width=\"15px\" src=\"./icon/plus.png\" alt=\"\">
</button>
</span>
</div>
</div>
<div class=\"col-md-3 bg-white\">
<h5 class=\"total my-5\">Total: <span id=\"total\">$ $price</span></h5>
</div>
<div class=\"col-md-1 bg-white\">
<button type=\"submit\" class=\"bg-white mt-5\" style=\"border: none; outline:none;\" name=\"remove\">
<img style=\"height:30px\" width=\"30px\" src=\"./icon/x.png\" alt=\"\">
</button>
</div>
</div>
</div>
</form>
";
echo $element;
}
Upvotes: 1
Views: 1481
Reputation: 142
Your click handler is looking at $quantity which is returning all of the quantity input fields not just the one corresponding the the button being clicked. Try something like this:
$buttonPlus.click(function() {
$(this).closest('.input-group').find('.quantity').val(Math.min(parseInt($quantity.val()) + 1, 999)).trigger('input');
});
In this example you're looking for the wrapping input group container and getting the input field from that specific container.
Upvotes: 1