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