简体   繁体   English

使用HTML中数据字段提取的变量进行计算

[英]Calculate with variables pulled by data fields from HTML

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. 问题是我无法获得javascript的总价,因为我总是得到NaN。 I thought its because those variables are interpreted as String but parseFloat or parseInt hasn't helped as well. 我认为是因为这些变量被解释为String,但parseFloat或parseInt并没有帮助。

Here is my HTML5: 这是我的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: 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/ JSFiddle: http : //jsfiddle.net/23owof84/

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/ 检查更改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€");
});

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

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