我在 .net-mvc 中构建,我想在一个文本框中减去两个数字并显示在 View (cshtml) 中的另一个文本框中。我已经尝试了所有方法,但无法弄清楚为什么它不起作用。
var a = parseInt(document.getElementById("sale").value);
var b = parseInt(document.getElementById("cost").value);
var c;
a.onkeyup = function() {
var c;
if (isNaN(a.value) == false) {
c = (parseInt(a.value) || 0) - (parseInt(b.value) || 0);
document.getElementById("profit").value = c;
}
}
b.onkeyup = function() {
if (isNaN(b.value) == false) {
c = (parseInt(a.value) || 0) - (parseInt(b.value) || 0);
document.getElementById("profit").value = c;
}
}
<div class="form-style-5">
<form method="get" action="InsertBattCalcDetails">
<fieldset>
<legend><span class="number">1</span> Insert Battery Calculations</legend>
Date: <input type="date" name="Date" /> <br /> Battery Value: <input type="number" name="Batt_value" /> <br /> Battery Sales: <input type="text" name="Batt_sales" id="sale" /> <br /> Battery Cost: <input type="text" name="Batt_cost" id="cost" /> <br /> Battery Profit: <input type="text" name="Batt_profit" id="profit" /> <br /> Battery Bought: <input type="number" name="Batt_bought" /> <br />
</fieldset>
<input type="submit" value="Submit" /> <input type="reset" value="Reset" />
</form>
</div>
最佳答案
a
和b
都应该保存对分别具有 ids sale 和 cost 的元素的引用。正如您定义的那样,它们只是数字值,在注册事件时没有任何意义,例如 onkeyup。
通过将 a
更改为 saleInput
并将 b
更改为 costInput
将使您的代码更具可读性:
var saleElement = document.getElementById("sale");
var costElement = document.getElementById("cost");
saleElement.onkeyup = calculateProfit;
costElement.onkeyup = calculateProfit;
function calculateProfit() {
let sale = parseInt(saleElement.value, 10);
let cost = parseInt(costElement.value, 10);
if(isNaN(sale) || isNaN(cost)) {
// either sale or cost are not numbers. profit cannot be calculated.
return;
}
let profitElement = document.getElementById("profit");
profitElement.value = sale - cost;
}
<div class="form-style-5">
<form method="get" action="InsertBattCalcDetails">
<fieldset>
<legend><span class="number">1</span> Insert Battery Calculations</legend>
Date: <input type="date" name="Date" /> <br />
Battery Value: <input type="number" name="Batt_value" /> <br />
Battery Sales: <input type="text" name="Batt_sales" id="sale" /> <br />
Battery Cost: <input type="text" name="Batt_cost" id="cost" /> <br />
Battery Profit: <input type="text" name="Batt_profit" id="profit" /> <br />
Battery Bought: <input type="number" name="Batt_bought" /> <br />
</fieldset>
<input type="submit" value="Submit" /> <input type="reset" value="Reset" />
</form>
</div>
关于javascript - 使用 JavaScript 在没有按钮的表单中添加两个数字(在 cshtml MVC 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56103678/