Question

Look at: http://jsfiddle.net/MLsAu/14/ in Asp.Net page_load , program calculate sum Price and Total Price and Sum Discount .but i want to calculate with jquery when user change one of dropdownlist values (quantity of products) . i know some of codes is wrong but i don't know where is wrong . for example , when user change first item quantity from 2 to 1 , SumPrice is wrong !

i tested this code , but it's not ok.

               var sumPrice = 0;
               $('tr').each(function () {
                   sumPrice += parseInt(quantity * parseInt($(this).closest('tr').find('.ffour').text()));
               });
               $('#txtSumPrice').html(sumPrice);
Was it helpful?

Solution

You have to set the sum total, discount and price to 0 within your change event each time, else it would take the last available value. Please find the corrected fiddle here.

$('.drop').on('change',function () {
    $('#txtSumDiscount').text('0');
    $('#txtSumPrice').text('0');
    $('#txtTotal').text('0');
    var tr = $(this).closest('tr');
    var price = $(tr).find('.ffour').html() - $(tr).find('.fthree').html();
    $(tr).find('.fone').html(price * $(this).val());

    var sum = 0, discount = 0, total =0;

    $(this).closest('#dvCart').find('tr td.fone').each(function(){
        var parent = $(this).parent();
        var q = parseFloat($(parent).find('select.drop').val());
        sum += parseFloat($(parent).find('td.ffour').text()) * q;
        discount += parseFloat($(parent).find('td.fthree').text()) * q;
    });

    $('#txtSumPrice').html(sum);
    $('#txtSumDiscount').html(discount);
    $('#txtTotal').html(sum - discount);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top