在 HTML/JavaScript 中减去两个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29317741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Subtract Two Numbers In HTML/JavaScript
提问by Ahmad
I am trying to subtract two numbers from an HTML Input form and populate the result into another input field using JavaScript. Unfortunately i am new to JavaScript so please be so kind to point me in the right direction. Here's my HTML code.
我正在尝试从 HTML 输入表单中减去两个数字,然后使用 JavaScript 将结果填充到另一个输入字段中。不幸的是,我是 JavaScript 新手,所以请指点我正确的方向。这是我的 HTML 代码。
<div class="form-group col-lg-6">
<label for="exampleInputText">Total Price</label>
<input type="text" name="totalval" class="form-control" id="totalval">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputText">Initial Deposit</label>
<input type="text" name="inideposit" class="form-control" id="inideposit">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputText">Outstanding Dues</label>
<input type="text" name="remainingval" class="form-control" id="remainingval" >
</div>
Here is my JavaScript code:
这是我的 JavaScript 代码:
<script type="text/javascript">
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
</script>
采纳答案by Alvaro Montoro
Your code works fine, so you'll just need to wrap your code in a function, and then call it every time that the input fields are modified (onchangeevent).
您的代码运行良好,因此您只需要将代码包装在一个函数中,然后在每次修改输入字段时调用它(onchange事件)。
<div class="form-group col-lg-6">
<label for="exampleInputText">Total Price</label>
<input type="text" name="totalval" class="form-control" id="totalval" onchange="updateDue()">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputText">Initial Deposit</label>
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputText">Outstanding Dues</label>
<input type="text" name="remainingval" class="form-control" id="remainingval">
</div>
Finally, to make sure they are numbers (I was getting some weird result when one of them was empty), add some code to make sure the values are numeric:
最后,为了确保它们是数字(当其中一个为空时,我得到了一些奇怪的结果),添加一些代码以确保这些值是数字:
function updateDue() {
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
}
You can see it on this JSFiddle: http://jsfiddle.net/sbu00cu2/
你可以在这个 JSFiddle 上看到它:http: //jsfiddle.net/sbu00cu2/

