Reputation: 18524
I wan't to calculate a Total price based on the selected quantity and the price. Therefore I use the data-property given by a button. The problem is that I can't calculate the totalprice with javascript because I always get NaN. I thought its because those variables are interpreted as String but parseFloat or parseInt hasn't helped as well.
Here is my HTML5:
<div class="checkout-meta">
<div class="checkout-info">
<strong>Total:</strong> 35,00€
</div>
<div class="checkout-cta">
<select class="quantity" name="quantity">
<option>
1
</option>
<option>
2
</option>
<option>
3
</option>
<option>
4
</option>
</select>
<a class="btn-1 ajax-popup" data-packageid="1"
data-price="35" data-region="EUW" href="checkout.php">
Purchase Now
</a>
</div>
</div>
JavaScript / jQuery:
$('.quantity').change(function(e){
var purchaseBtn = $(this).parent().find('.btn-1');
var price = parseFloat(purchaseBtn.data('price'));
var quantity = parseFloat(purchaseBtn.data('quantity'));
var total = price*quantity;
$(this).parent().parent().find('.checkout-info').html("<strong>Total:</strong> " + total + ",00€");
});
JSFiddle: http://jsfiddle.net/23owof84/
Upvotes: 0
Views: 50
Reputation: 517
You were taking the quantity out of the button
var quantity = parseFloat(purchaseBtn.data('quantity'));
But you need to take it from the select
var quantity = parseFloat($(".quantity option:selected" ).text());
Here is the full snippet. Check the changes http://jsfiddle.net/23owof84/6/
$('.quantity').change(function(e){
var purchaseBtn = $(this).parent().find('.btn-1');
var price = parseFloat(purchaseBtn.data('price'));
var quantity = parseFloat($(this).find('option:selected').text());
var total = price*quantity;
$(this).parent().parent().find('.checkout-info').html("<strong>Total:</strong> " + total + ",00€");
});
Upvotes: 2