JS script to calculate the sum of the amount calculates the wrong

I prepared this jsfiddle which illustrates how my script calculates twice as much as the sum of each selected option attribute price. Please help me solve this problem.

optionsamount is incorrect, I mean, computed twice. Why? 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); } 
+5
source share
2 answers

Try it,

 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); 
+3
source

try it

 function update_amounts(){ var sum = 0.0; $('#basketorder > tbody > .product').each(function() { var optionsamount = 0.0; $('.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); 

}

0
source

Source: https://habr.com/ru/post/1209233/


All Articles