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

Calculate with variables pulled by data fields from HTML

本文关键字:变量 计算 提取 HTML 数据 字段 使用      更新时间:2023-09-26

我不想根据所选数量和价格计算总价。因此,我使用由按钮提供的数据属性。问题是我不能用javascript计算总价,因为我总是得到NaN。我认为这是因为这些变量被解释为String,但parseFloat或parseInt也没有帮助。

这是我的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/

您正在从按钮中取出数量

var quantity = parseFloat(purchaseBtn.data('quantity'));

但你需要从选择的中提取

var quantity = parseFloat($(".quantity option:selected" ).text());

这是完整的片段。检查更改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€");
});