在一个表单中进行输入值的求和和乘积

3

我希望构建一个实时的JavaScript表单来计算价格。 这个表单包含4个框:

<input type="text" id="hours" oninput="calculate()">
<input type="text" id="cars" oninput="calculate()">
<input type="text" id="1" oninput="calculate()">
<input type="text" id="2" oninput="calculate()">

“1”和“2”的值是对“汽车”和“小时”的加法和乘法运算。
例如:20 + 30 * 2 * 2
我尝试了这个,但它没有起作用。
<script type="text/javascript">
    function calculate() {
        var myBox1 = document.getElementById('box1').value; 
        var myBox2 = document.getElementById('box2').value;
        var myBox3 = document.getElementById('box3').value;
            var myBox4 = document.getElementById('box4').value;
        var result = document.getElementById('result'); 
        var myResult = (myBox1+myBox2)*myBox3*myBox4;
        result.value = myResult;

    }


</script> 

我可以看到元素选择器中的错误。 - Anil Gupta
只要你只有这些输入,你也可以做一些简单和易于维护的事情,就像这样:http://jsfiddle.net/ezpjkexv/1/ - briosheje
2个回答

1
你的问题在于value属性返回DOMString,在这种情况下+符号将它们连接起来。你需要将值转换为整数,例如使用parseInt函数:
var myResult = (parseInt( myBox2, 10 )+parseInt( myBox2, 10 ))*parseInt( myBox3, 10 )*parseInt( myBox4, 10 );

似乎你的id属性与JS中获取的不相等。应该是:
<input type="text" id="box1" oninput="calculate()">
<input type="text" id="box2" oninput="calculate()">
<input type="text" id="box3" oninput="calculate()">
<input type="text" id="box4" oninput="calculate()">

工作示例:

function calculate() {
  var myBox1 = document.getElementById('box1').value; 
  var myBox2 = document.getElementById('box2').value;
  var myBox3 = document.getElementById('box3').value;
  var myBox4 = document.getElementById('box4').value;
  var result = document.getElementById('result'); 
  var myResult = (parseInt( myBox2, 10 )+parseInt( myBox2, 10 ))*parseInt( myBox3, 10 )*parseInt( myBox4, 10 );
  result.value = myResult;
}
<input type="text" id="box1" oninput="calculate()">
<input type="text" id="box2" oninput="calculate()">
<input type="text" id="box3" oninput="calculate()">
<input type="text" id="box4" oninput="calculate()">
<input type="text" id="result">


1

正如Antyrat所提到的那样,您没有解析输入,这可能是一个原因,另一个原因是如果没有其他输入,您可能会得到null。

<script type="text/javascript">
    function calculate() {
        var myBox1 = document.getElementById('box1').value; 
        var myBox2 = document.getElementById('box2').value;
        var myBox3 = document.getElementById('box3').value;
        var myBox4 = document.getElementById('box4').value;
        var result = document.getElementById('result'); 
        var myResult;
        if(myBox1.length != 0 && myBox2.length != 0 && myBox3.length != 0 && myBox4.length != 0){
           myResult = (parseInt( myBox2, 10 )+parseInt( myBox2, 10 ))*parseInt( myBox3, 10 )*parseInt( myBox4, 10 );
       }else{
           myResult = 0;
        }

        result.value = myResult;

    }


</script> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接