说我有以下内容:
目前,当两个输入字段更新时,它们相互依赖以更新最终数量。如何使它即使一个字段为空,总计仍然会更新?
(rightsTotal永远不会为空)
function calculateTotal() {
var number1 = parseInt(document.getElementById('travelField').value) + parseInt(document.getElementById('giftField').value) + rightsTotal;
document.getElementById("grandTotal").innerHTML = '£' + number1 ;
}
谢谢!
答案 0 :(得分:2)
您应该检查parseInt的结果是否为数字。当结果不是数字时,isNan()
返回true,因此我们可以使用三元运算符来提供0而不是NaN。
var number1 = parseInt(document.getElementById('travelField').value);
var number2 = parseInt(document.getElementById('giftField').value);
var result = (isNan(number1) ? 0 : number1) + (isNan(number2) ? 0 : number2) + rightsTotal
答案 1 :(得分:2)
parseInt
), NaN
将返回""
(不是数字)。
您可以将parseInt
与||
(或)表达式结合使用,如果您的值不是数字,则返回0
:
function calculateTotal() {
var travelField = parseInt(document.getElementById('travelField').value) || 0;
var giftField = parseInt(document.getElementById('giftField').value) || 0
var number1 = travelField + giftField + rightsTotal;
document.getElementById("grandTotal").innerHTML = '£' + number1 ;
}
答案 2 :(得分:0)
function calculateTotal() {
var number1 = (isNan(parseInt(document.getElementById('travelField').value))) ? 0 : parseInt(document.getElementById('travelField').value); // set value to 0 if nothing present in the textfield
var number2 = (isNan(parseInt(document.getElementById('giftField').value))) ? 0 : parseInt(document.getElementById('giftField').value); // set value to 0 if nothing present in the textfield
var total = number1 + number2 + rightsTotal;
document.getElementById("grandTotal").innerHTML = '£' + total ;
}