Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS script to calculates sum of amount calculates wrong

I have prepared this jsfiddle that ilustrates how my script calculate twice the sum of each selected option attribute price. Please help me to solve this issue.

optionsamount is wrong, I mean is calculated twice.. Why is that? Thanks

function update_amounts(){
    var sum = 0.0;
    var optionsamount = 0.0;

    $('#basketorder > tbody  > .product').each(function() {

        $('.selectedoptionselect option:selected').each(function(){
            optprice = $(this).attr('price');
            optionsamount+= parseFloat(optprice);    
        })

        var qty = $(this).find('.qty option:selected').val();
        var price = $(this).find('.price').val();
        var amount = (qty*price);
        sum+= (amount + optionsamount);

        $(this).find('.amount').text(''+ amount.toFixed(2));
    });

    $('.total').text(sum);
}
like image 960
Europeuser Avatar asked Oct 19 '22 20:10

Europeuser


1 Answers

Try this,

function update_amounts(){
var sum = 0.0;

$('#basketorder > tbody  > .product').each(function() {

    var optionsamount = 0.0;


    $(this).find('.selectedoptionselect option:selected').each(function(){
        optprice = $(this).attr('price');
        optionsamount+= parseFloat(optprice);    
    })

    var qty = $(this).find('.qty option:selected').val();
    var price = $(this).find('.price').val();
    var amount = (qty*price);
    sum+= (amount + optionsamount);

    $(this).find('.amount').text(''+ amount.toFixed(2));
});

$('.total').text(sum);
like image 147
Vaibhav J Avatar answered Oct 22 '22 09:10

Vaibhav J