我想写一些JavaScript/jQuery来总结在多个文本框中输入的值。使用复选框来决定哪些输入框值总和
每个输入框都有一个与其关联的复选框,并根据该复选框将该值添加到总数中。例如,如果用户选择Activity fees
和Transport fees
,则他们应该加起来,如果他选择Misc fees
也将加起来,并且如果他然后取消选中Misc fees
,则应该再次减去该值。
function optionalfee() {
var total = 0;
var fee = document.getElementsById('optional1');
for (var i = 0; i < fee.length; ++i) {
if (optional1.checked == true)
document.getElementById('optional').value = fee;
total += parseFloat(fee.value);
}
} else {
total -= parseFloat(fee.value);
}
//alert(total);
document.getElementById('toptional').value = total;
}
Include Activity fees <input type="checkbox" id="optional1" /><input type="number" id="optional" name="afees"><br><br>
Include Transport fees <input type="checkbox" id="optional1" /><input type="number" id="optional" name="tfees"><br><br>
Include Misc fees <input type="checkbox" id="optional1" /><input type="number" id="optional" name="mfees"><br><br>
Include Olympiad fees <input type="checkbox" id="optional1" /><input type="number" id="optional" name="ofees"><br><br>
Optional fees total <input type="number" id="toptional" name="toptional" class="toptional" readonly>
你应该只有一个元素与'id =“optional1”' –
“似乎无法让它工作”并不是对问题的有意义的描述。它以什么方式失败?另外,如另一条评论(可能还会更多)所述,HTML无效。所以任何JavaScript的行为都将被定义,直到更正。 'id's需要是唯一的。 – David
格式化你的代码表明你有语法错误 - 缺少'if(optional1.checked == true)'之后的括号,例如 – mplungjan