[英]How to change the display value of two text boxes through the input value of another text box using javascript?
[英]How do I calculate two text boxes and display the answer in another?
我正在尝试添加两个文本框并在第三个中显示结果,每当我尝试添加第三个框时,它都会使其无效。 有什么建议? 这是我的代码!
<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>
尝试.....
$("#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">
我看不出任何错误,除了;
或}
。
最好使用onchange
或其他事件事件来删除点击以获得更好的 ui/ux。
但是你可以用angularjs
更好地做到这一点。你可以为每个输入使用ng-model
并在第三个输入中写入{{model1+model2}}
。
你也可以用vue.js
不同的是你应该使用vmodel
而不是ng-model
。
getElementById('num1')
此处的id
应在引号中,否则将被视为变量。
你也忘记了最后的}
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.