[英]How do I calculate two text boxes and display the answer in another?
I am trying to add the two text boxes and show the result in a third, whenever I try to add the third box, it makes it invalid.我正在尝试添加两个文本框并在第三个中显示结果,每当我尝试添加第三个框时,它都会使其无效。 Any suggestions?
有什么建议? Here is my code!
这是我的代码!
<br>
<br>
<p4>Calculate Two Fields</p4>
<p4 id="answer"></p4>
<br>
<br>
Number 1<input type="text" id="num1" <br>
<br>
Number 2<input type="text" id="num2" <br>
<br>
<button onclick="calculate()">Calculate</button>
<script>
function calculate() {
var field1 = document.getElementById(num1).value;
var field2 = document.getElementById(num2).value;
var result = parseFloat(field1) + parseFloat(field2)
if (!isNaN(result))
{
document.getElementById("answer").innerHTML = "The answer is " + result;
}
</script>
Try.....尝试.....
$("#second").keyup(function() { var total = 0; $('.smtab_tot').each(function(_i, e) { var val = parseFloat(e.value); if (!isNaN(val)) total += val; }); $('#total').val(total); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> input 1 : <input type="number" class="smtab_tot" id="first"> <br> input 2 : <input type="number" class="smtab_tot" id="second"> <br> total : <input type="text" id="total">
I cant see any mistake except ;
我看不出任何错误,除了
;
or }
.或
}
。
Its better to use onchange
or other events events to remove clicking to get better ui/ux.最好使用
onchange
或其他事件事件来删除点击以获得更好的 ui/ux。
But you can do it with angularjs
better.you can use ng-model
for each input and in third input write {{model1+model2}}
.但是你可以用
angularjs
更好地做到这一点。你可以为每个输入使用ng-model
并在第三个输入中写入{{model1+model2}}
。
You can do it with vue.js
too .the different is that you should use vmodel
instead of ng-model
.你也可以用
vue.js
不同的是你应该使用vmodel
而不是ng-model
。
getElementById('num1')
here id
should be in quote, otherwise it will be treated as variable. getElementById('num1')
此处的id
应在引号中,否则将被视为变量。
Also you forgot the }
at the end你也忘记了最后的
}
function calculate() { var field1 = document.getElementById('num1').value; var field2 = document.getElementById('num2').value; var result = parseFloat(field1) + parseFloat(field2); if (!isNaN(result)) { document.getElementById("answer").textContent= "The answer is " + result; } }
<br> <br> <p4>Calculate Two Fields</p4> <p4 id="answer"></p4> <br> <br> Number 1<input type="text" id="num1" <br> <br> Number 2<input type="text" id="num2" <br> <br> <button onclick="calculate()">Calculate</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.