Osu Osu - 11 days ago 7
Javascript Question

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
.

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?

JS FIDDLE

http://jsfiddle.net/wy5hy42x/

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

// 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');
});

Answer

You just need to remove var keyword from this line:

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.

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. 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/