Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
174
rated 0 times [  181] [ 7]  / answers: 1 / hits: 19797  / 10 Years ago, wed, february 26, 2014, 12:00:00

I have prepared this jsfiddle



The problem is that I have many rows containing product qty * price = sub total
This also must dynamically calculate grand total for all sub total amounts. And the biggest problem is the trigger since we may not have change trigger on the qty select fields.. really complicated for me.
I am so far stacked here:



$(document).ready(function() {    
var qty=$('.qty').val();
var price = $('.price').val();
var sum = 0;

$('.amount').each(function() {
sum += parseFloat($(this).text());
});
});


Please give me idea for:




  1. Which trigger to use so it can calculate on page load as well and if qty dropdown is changed too.

  2. How to calculate each row first



thank you for your help and time in advance!


More From » jquery

 Answers
18

You have your answer here: http://jsfiddle.net/kY98p/10/



I changed the html to use the tags thead and tfoot for header and footer



Its just a cycle over the lines where you get the quantity and price and update the amount...



Here is the function that you should call:



function update_amounts()
{
var sum = 0.0;
$('#myTable > tbody > tr').each(function() {
var qty = $(this).find('option:selected').val();
var price = $(this).find('.price').val();
var amount = (qty*price)
sum+=amount;
$(this).find('.amount').text(''+amount);
});
//just update the total to sum
$('.total').text(sum);
}


And the event that you need is:



$('.qty').change(function() {
update_amounts();
});


UPDATE: jsfiddle with total: http://jsfiddle.net/kY98p/11/


[#72291] Tuesday, February 25, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrence

Total Points: 120
Total Questions: 115
Total Answers: 87

Location: England
Member since Fri, May 22, 2020
4 Years ago
terrence questions
Sat, Jun 5, 21, 00:00, 3 Years ago
Wed, Jun 17, 20, 00:00, 4 Years ago
;