我正在尝试添加一些表单字段,但与我尝试的数组无关紧要,如果再次检查,它将不断加总值,仅在以下情况下,我才需要它来将复选框中的值与金额中的输入值相加如果未检查的值减去还是不增加,我们将不胜感激。
<div class="hire-accessories"><input type="checkbox" name="baby-st" id="baby-st" class="checkbox" value="5"/>Baby Seat 0-2 Year £5(Day)</div>
<div class="hire-accessories"><input type="checkbox" name="child-st" id="child-st" class="checkbox" value="5" />Child Seat 3-7 Year Seat £7(Day)</div>
<div class="hire-accessories"><input type="checkbox" name="gps" id="gps" class="checkbox" value="5" />TomTom GPS</div>
<div class="hire-accessories"><input type="checkbox" name="bike-rack" id="bike-rack" class="checkbox" value="10" />Bike Rack</div>
<div class="hire-accessories"><input type="checkbox" name="mbike" id="mbike" class="checkbox" value="5" />Montainbike</div>
<input type="text" name="Amount" id="Amount" value="20" readonly class="cat_textbox" />
我的JS如下:
var updateTotal = function () {
var Amount = parseFloat(document.getElementById("Amount").value);
var total = 0;
total += ($('input[name=baby-st]:checked').length > 0) ? parseFloat($('input[name=baby-st]:checked').val()) : 0;
total += ($('input[name=child-st]:checked').length > 0) ? parseFloat($('input[name=child-st]:checked').val()) : 0;
total += ($('input[name=gps]:checked').length > 0) ? parseFloat($('input[name=gps]:checked').val()) : 0;
total += ($('input[name=bike-rack]:checked').length > 0) ? parseFloat($('input[name=bike-rack]:checked').val()) : 0;
total += ($('input[name=mbike]:checked').length > 0) ? parseFloat($('input[name=mbike]:checked').val()) : 0;
document.getElementById('Amount').value = Amount+total;
};
$('#baby-st, #child-st, #gps, #bike-rack, #mbike').change(function() {
if(this.checked)
{
}
updateTotal();
});
THE DEMO
最佳答案
将您的金额声明移到updateTotal函数之外。
var Amount = parseFloat(document.getElementById("Amount").value);
var updateTotal = function () {
var total = 0;
total += ($('input[name=baby-st]:checked').length > 0) ? parseFloat($('input[name=baby-st]:checked').val()) : 0;
total += ($('input[name=child-st]:checked').length > 0) ? parseFloat($('input[name=child-st]:checked').val()) : 0;
total += ($('input[name=gps]:checked').length > 0) ? parseFloat($('input[name=gps]:checked').val()) : 0;
total += ($('input[name=bike-rack]:checked').length > 0) ? parseFloat($('input[name=bike-rack]:checked').val()) : 0;
total += ($('input[name=mbike]:checked').length > 0) ? parseFloat($('input[name=mbike]:checked').val()) : 0;
document.getElementById('Amount').value = Amount+total;
};
$('#baby-st, #child-st, #gps, #bike-rack, #mbike').change(function() {
if(this.checked)
{
}
updateTotal();
});
DEMO HERE
关于javascript - Javascript不断增加总数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28618268/