Reputation: 91
I am using the code below to multiply the quantity by the price. The code works fine but when I have more than one row it adds the price from the first row to the second row
How can I make the price show only that row and not previous rows?
I have create a fiddle to show what I am trying to do
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>demo</title>
<script type='text/javascript' src='//code.jquery.com/jquery-1.9.1.js'></script>
<style type='text/css'>
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$('.minus, .plus').click(function (e) {
e.preventDefault();
var $input = $(this).siblings('.qty');
var val = parseInt($input.val(), 10);
$input.val(val + ($(this).hasClass('minus') ? -1 : 1));
});
});//]]>
</script>
<script type='text/javascript'>//<![CDATA[
$(function(){
$('.minus, .plus').click(function () {
var sibs = $(this).siblings();
var quantity = $('.qty').val();
var priceItem = sibs.filter(".price").val();
var total2 = quantity * priceItem;
var total = (+total2 + +priceItem);
sibs.filter(".total").val(total);
});
});//]]>
</script>
</head>
<body>
<?php
$x=1;
while($x<=5)
{
?>
<div>Qty:
<span class='minus' class="signrm">—</span> <input type="text" name="qty" class="txt qty" value="1" /> <span class='plus' >+</span>
<br/>Price:
<input type="text" name="price" class="txt price" value="500" />
<br/>Total:
<input type="text" name="total" class="txt total" value="500" />
</div>
<?php
$x++; } ?>
</body>
</html>
Upvotes: 1
Views: 771
Reputation: 335
Your on the right track, Just make sure your getting all the values from the siblings of the button. Also your window on load click event isn't working. I wasn't able to see the same issue your having. But i would do all the code in one click event instead of two.
Here's a fiddle example and below is the code.
$(function () {
$('.minus, .plus').click(function () {
var $qty = $(this).siblings('.qty');
var qtyCounter = parseInt($qty.val());
if($(this).hasClass('plus'))
qtyCounter++;
else
qtyCounter--;
$qty.val(qtyCounter);
var pricePerUnit = $(this).siblings('.price').val();
var quantity = $(this).siblings('.qty').val();
var total = quantity * pricePerUnit;
$(this).siblings('.total').val(total);
});
});
Upvotes: 2