我有一套用户可以选择的复选框。每次检查一本书时,价格都会增加。我还需要添加相应的重量。我修改了this very useful example,但没有用。
<label class="checkbox" for="Checkbox1">
<input value="50" type="checkbox" class="sum" data-toggle="checkbox"> Instagram
</label>
<label class="checkbox">
<input value="50" bweight=".4" type="checkbox" class="sum" data-toggle="checkbox"> Review site monitoring
</label>
<label class="checkbox">
<input value="30" bweight=".2" type="checkbox" class="sum" data-toggle="checkbox"> Google+
</label>
<label class="checkbox">
<input value="20" bweight=".6" type="checkbox" class="sum" data-toggle="checkbox"> LinkedIn
</label>
<div class="card-charge-info">
<span id="payment-total">0</span>
</div>
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total');
totwgt = document.getElementById('payment-w');
for (var i = 0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
var add = this.wgt * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + add
totwgt.innerHTML = parseFloat(total1.innerHTML) + add
}
}
答案 0 :(得分:1)
您的代码中存在多个问题。首先,您在两个位置定义add
变量,一个用于另一个值的另一个值,因此您的计算从那里被打破。另请注意,bweight
不是input
元素的有效属性。要添加自己的元数据,您应该使用data-*
属性。
试试这个:
var inputs = document.getElementsByClassName('sum'),
totalValue = document.getElementById('payment-total'),
totalWeight = document.getElementById('payment-w');
for (var i = 0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var value = parseFloat(this.value);
var weight = parseFloat(this.dataset.weight);
totalValue.innerHTML = parseFloat(totalValue.innerHTML) + value
totalWeight.innerHTML = parseFloat(totalWeight.innerHTML) + weight
}
}
当您使用jQuery标记此问题时,这是一个有效的实现
var $inputs = $('.sum'),
$totalValue = $('#payment-total'),
$totalWeight = $('#payment-w');
$inputs.change(function() {
var value = parseFloat(this.value);
var weight = parseFloat($(this).data('weight'));
$totalValue.text(function(i, text) {
return parseFloat(text) + value;
});
$totalWeight.text(function(i, text) {
return parseFloat(text) + weight;
});
})
答案 1 :(得分:0)
你几乎没有问题:
add
变量total1
中输错了它应该是totwgt
payment-w
id this.wgt
您应该使用this.getAttribute('bweight')