简体   繁体   English

使用jQuery计算购物车总计

[英]Calculating cart total using jQuery

I'm trying to do something I thought would be simple (!), but having trouble. 我正在尝试做一些我认为很简单的事情(!),但遇到了麻烦。 Every time a user updates the form below, I want to update the cart total by multiplying the quantity (input values) by the data attribute unit-price . 每次用户更新下面的表格时,我想通过将数量(输入值)乘以数据属性unit-price来更新购物车总额。

I thought I would just need to loop through each input and grab the value and unit-price so I can multiply them together to create a total, but I'm the subtotal is returning '0'... any ideas of what I'm doing wrong? 我以为我只需要遍历每个输入并获取值和unit-price这样我就可以将它们相乘以创建一个总计,但是我小计返回的是“ 0” ...关于我的任何想法我做错了吗?

JS FIDDLE JS菲德尔

http://jsfiddle.net/wy5hy42x/ http://jsfiddle.net/wy5hy42x/

HTML HTML

<form action="" id="form">
    <div class="cart-row">
        <p>Product name</p>
        <label for="updates">Quantity:</label>
        <input type="number" name="updates[]" value="2" min="0" data-unit-price="18.00" class="cart-variant--quantity_input"><br />
        &pound;18 each
    </div>

    <div class="cart-row">
        <p>Product name</p>
        <label for="updates">Quantity:</label>
        <input type="number" name="updates[]" value="4" min="0" data-unit-price="31.00" class="cart-variant--quantity_input"><br />
        &pound;31 each
    </div>

    <div class="cart-row">
        <p>Product name</p>
        <label for="updates">Quantity:</label>
        <input type="number" name="updates[]" value="4" min="0" data-unit-price="12.00" class="cart-variant--quantity_input"><br />
        &pound;12 each
    </div>
    <input type="submit" value="submit" />
</form>

JQUERY JQUERY

// Update final price on quantity change
$('.cart-variant--quantity_input').on("change", function() {
  var st            = 0;
  $('.cart-row').each(function() {
    var i           = $('.cart-variant--quantity_input');
    var up          = $(i).data('unit-price');
    var q           = $(i).val();
    var st          = st + (up * q);
  });
  // Subtotal price
  alert('Cart updated. Subtotal : ' + st + 'GBP');
});

You just need to remove var keyword from this line: 您只需要从此行中删除var关键字:

var st = st + (up * q);
// ^-- remove var in fron of st

otherwise you create a local variable inside a $.each callback and never update outer st value. 否则,您将在$ .each回调内创建局部变量,并且永远不要更新外部st值。

UPD. UPD。 (credits to Dustin Hoffner for this catch) The second problem is that you need to find .cart-variant--quantity_input elements within current .cart-row container. (此收获归Dustin Hoffner所有。)第二个问题是,您需要在当前.cart-row容器中找到.cart-variant--quantity_input元素。 For example, by providing a context for selector: 例如,通过为选择器提供上下文:

var i = $('.cart-variant--quantity_input', this);

All together it will become 一起将成为

$('.cart-variant--quantity_input').on("change", function () {
    var st = 0;
    $('.cart-row').each(function () {
        var i = $('.cart-variant--quantity_input', this);
        var up = $(i).data('unit-price');
        var q = $(i).val();
        st = st + (up * q);
    });
    // Subtotal price
    alert('Cart updated. Subtotal : ' + st + 'GBP');
});

Demo: http://jsfiddle.net/wy5hy42x/9/ 演示: http //jsfiddle.net/wy5hy42x/9/

First answer is not complete: 第一个答案不完整:

$('.cart-row').each(function(k) {
        var i           = $('.cart-variant--quantity_input')[k];
        var up          = parseFloat($(i).data('unit-price'));
        var q           = parseInt($(i).val());
        st          += (up * q);
      });

Edit: Changed parseInt to parseFloat (thanks to War10ck) (see his comment for the reason) 编辑:将parseInt更改为parseFloat(由于War10ck)(请参阅他的评论以了解原因)

I removed the 'var' because you would overwrite in each loop. 我删除了“ var”,因为您将在每个循环中覆盖。

Furthermore you will not calculate correctly: 此外,您将无法正确计算:

var i           = $('.cart-variant--quantity_input');

This will always give you the first element. 这将始终为您提供第一个要素。 But you have more than one, so you need to get only the actual one from the returned array. 但是您不止一个,因此您只需要从返回的数组中获取实际的一个即可。

$('.cart-row').each(function(k) {
        var i           = $('.cart-variant--quantity_input')[k];

You can do this by taking the counter 'k' from your loop and get the right element with '[k]'. 您可以通过从循环中获取计数器“ k”并使用“ [k]”获得正确的元素来实现。

In your each loop you need to take the current input, instead of the first one: each循环中,您需要采用当前输入,而不是第一个输入:

$('.cart-row').each(function(e) {
    var i           = $('.cart-variant--quantity_input').eq(e); // get item in the e position
    var up          = $(i).data('unit-price');
    var q           = $(i).val();
    st          = st + (up * q);
});

Also you need to remove the var keyword before st, as its creating a new st variable instead of updating the outer one. 另外,您还需要在st之前删除var关键字,因为它会创建一个新的st变量,而不是更新外部变量。

See this fiddle 看到这个小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM