jQuery计算有效,但在正确值之前添加了不正确的值

时间:2019-01-22 12:25:10

标签: javascript jquery

我一直在使用此计算器,并且在某种意义上说它正在正确地计算字段价格并显示它。但是,问题在于,它似乎将正确的答案附加到另一个值(大概是从数据价格中获取的,因为它们相互关联)。

这是我的代码:

var updateTotal = function() {
 
    var sumtotal;
       var sum = 0;
    //Add each product price to total
    $(".extraproduct").each(function() {
        var extra_price = $(this).data('price');
        var quantity = $('.extraQuantity', this).val();
   
        //Total for one product
        var subtotal = extra_price*quantity;     
         //Round to 2 decimal places.
        subtotal = subtotal.toFixed(2);      
        //Display subtotal in HTML element
        $('.productTotal', this).html(subtotal);
    });
    // total
       $('.productTotal').each(function() {
        sum += Number($(this).html());
    }); 
    
    $('#sum').html(sum.toFixed(2));
};
//Update total when quantity changes
$(".extraQuantity").bind("keyup change", function() {
    updateTotal();
});
//Update totals when page first loads
updateTotal();
// set this from local
    $('span.productTotal').each(function() {
        $(this).before("£")
    }); 
// unit price
   $('.extraproduct span').each(function() {
       var $price = $(this).parents("div").data('price');
      $(this).before($price);
    }); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<span class="quote-label">Product 1</span>
<div class="input-wrap currency extraproduct" data-price="450.00">
<input type="number" class="extraQuantity" value="0"  min="1" max="20" />
<span class="productTotal"></span>
</div>
                
 <span class="quote-label">Product 2</span>
<div class="input-wrap currency extraproduct" data-price="10.00">
<input type="number" class="extraQuantity" value="0"  min="1" max="20" />
<span class="productTotal"></span>
</div>


            
 <span class="quote-label">Additional Product</span>
<div class="input-wrap checkbox-wrap extraproduct" data-price="5.00"><input type="checkbox" class="extraQuantity" value="0" />
<span class="productTotal"></span>
</div>

<div id="total">Total: £<span id="sum">0.00</span> </div>

https://jsfiddle.net/DigitalAdam/5fLb0vnp/26/

我认为这可能与subtotal.toFixed部分有关,但是在调整或删除该部分时没有运气。任何帮助表示赞赏。 问候

1 个答案:

答案 0 :(得分:1)

非常简单的解决方案: 您只是使用.productTotal跨度来计算内容。您可以将显示设置为无。它仍然可以用于计算,但现在将显示:

.productTotal {
  display: none;
}