我正在使用以下代码添加文本框值,如果没有给出任何文本框值,它会在总文本框中显示NaN如何避免它
<script>
function totalValue()
{
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var d = parseFloat(a)+ parseFloat(b)+ parseFloat(c);
document.getElementById("total").value = d;
}
</script>
答案 0 :(得分:6)
试试这个:
<script>
function totalValue()
{
var a = document.getElementById("a").value || 0;
var b = document.getElementById("b").value || 0;
var c = document.getElementById("c").value || 0;
var d = parseFloat(a)+ parseFloat(b)+ parseFloat(c);
document.getElementById("total").value = d;
}
</script>
答案 1 :(得分:1)
您可以将0
附加到字符串:
<script>
function totalValue()
{
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var d = parseFloat('0' + a)+ parseFloat('0' + b)+ parseFloat('0' + c);
document.getElementById("total").value = d;
}
</script>
答案 2 :(得分:0)
<script>
//checks if given text in text box is a number or unwanted string
filterInt = function (value)
{
if(/^\-?[0-9]+$/.test(value))
return Number(value);
return NaN;
}
function totalValue()
{
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
a=filterInt(a)||0; //if it is a string, convert it to a Nan and then if NaN, convert to zero
b=filterInt(b)||0;
c=filterInt(c)||0;
var d = parseFloat(a)+ parseFloat(b)+ parseFloat(c);
document.getElementById("total").value = d;
}