0

我正在使用以下代码添加文本框值如果任何文本框没有给出值它在总文本框中显示 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>
4

3 回答 3

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>

小提琴:http: //jsfiddle.net/AvzwM/

于 2013-07-31T07:21:49.533 回答
1

您可以将 a 附加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>
于 2013-07-31T07:33:21.093 回答
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;
 }

于 2013-07-31T07:23:17.463 回答