Reputation: 298
I Want update the total of all the products in the cart page when quantity is updated. what I tried is
$d=$table.each(function(){
return Number($(this).find('.cart_price>p>span').html())*Number($(this).find('.cart_quantity_input').val());
}).toArray();
alert($d.length);
but seems its only taking the value from the first product only
I tried .map()
yet same result.
I even tried total+=
instead of return
(total=0
initialized at first) yet its returning value only from first <tr>
.
<tr>
's of my HTLM inside <table>
looks like:
<tr>
<td class="cart_product">
...
</td>
<td class="cart_description">
...
</td>
<td class="cart_price">
<p>₹<span>20</span></p>
</td>
<td class="cart_quantity">
<div class="cart_quantity_button">
<a class="cart_quantity_up" href="#"> + </a>
<input class="cart_quantity_input" type="text" name="quantity" value="8" autocomplete="off" size="2">
<a class="cart_quantity_down" href="#"> - </a>
</div>
</td>
<td class="cart_total">
<p class="cart_total_price"> ₹<span>160</span></p>
</td>
<td class="cart_delete">
...
</td>
</tr>
I just need the sum of each (cart_price>span>p)*(.cart_quantity_input.val())
.
PS:alert($d.length);
is just to check no of tr's while testing but I need sum not count
Upvotes: 0
Views: 111
Reputation: 2694
You need to first iterate over each tr then find the values .
$array=$table.find('tr').each(function(){
var price = Number($(this).find('.cart_price>p>span').html());
var qty = Number($(this).find('.cart_quantity_input').val());
return price*qty;
}).toArray();
alert($array.length);
Or to calculate Sum:
total=0;
$table.find('tr').each(function(){
var price = Number($(this).find('.cart_price>p>span').html());
var qty = Number($(this).find('.cart_quantity_input').val());
total+= price*qty;
});
alert(total);
Upvotes: 2
Reputation: 29
function getTotalPrice(){
var quantity =$('#cart_quantity_input').val();
var price= $('#cart_price').text();
var total = quantity * price;
alert(total);
}
Just try using id's this worked for me.
Upvotes: -1
Reputation: 388316
You can iterate over each tr
in the table and sum op the values
var sum = 0;
$table.find('tr').each(function () {
sum += ($(this).find('.cart_price > p > span').text() * $(this).find('.cart_quantity_input').val()) || 0;
});
alert(sum)
Upvotes: 0
Reputation: 6025
Assuming $table
is a your table $table.each()
will only run once on the table.
To have your function execute for each table row use
$table.find('tr').each()
Upvotes: 0