如何使用HTML页面中的值计算JavaScript中的值?

时间:2013-03-05 19:40:13

标签: javascript html

我试图在js中计算一个简单的乘法,如下所示:
A * B = C
D * E = F
G * H = I
总计= C + F + I

然而,总计大于预期。我的乘法是否有问题,或者我是否错误地从页面读取值?

以下是我的代码:

<html>
<head>
<script>
  calculate = function(totalElement)
  {
      if (totalElement)
      {
          var calculation  = '';
          var overall = '';
          var fields = new Array();
          var theElement = document.getElementById(totalElement);
          var userInputs = myform.elements;
          var the_type = '';
          for (var f = 0; f < userInputs.length; f++)
          {
              if (userInputs[f].className=='special_value')
              {
                 if(userInputs[f].value != "")
                 {
                     document.getElementById("price4").value+=+userInputs[f].value;

                 }           

              }
          }


      }
  }
</script>
</head>
<body>
<form name="myform">
A<input onKeyPress="calculate('total');" onBlur="calculate('total');" class="special_value" value="" type="text" name="price"> 
B<input onKeyPress="calculate('total');" onBlur="calculate('total');" class="special_value" type="text" value="" name="price2"> 
C<input onKeyPress="calculate('total');" onBlur="calculate('total');" class="special_value" type="text"value=""  name="price4" id="price4"> <Br/>
D<input onKeyPress="calculate('total');" onBlur="calculate('total');" class="special_value" value="" type="text" name="price5"> 
E<input onKeyPress="calculate('total');" onBlur="calculate('total');" class="special_value" type="text" value="" name="price6"> 
F<input onKeyPress="calculate('total');" onBlur="calculate('total');" class="special_value" type="text"value=""  name="price7" id="price7"> <Br/>
Total<input class="special_value" value="" id="total" type="text" name="total"> <Br/>
<!-- <div id="total"></div> -->
<input onClick="calculate('total');" type="button" name="button" value="re-calculate">
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:5)

document.getElementById("price4").value是一个字符串。你可能会连接字符串,而不是用它们做数学。

尝试:parseFloat(document.getElementById("price4").value)