这是我的代码:
function credit() {
//storing value of grandTotal in txtGrandTotal.
var txtGrandTotal = $("#txtGraTot").val();
//here resetting value of grandTotal to 0.00
var txtGraTotal = document.getElementById('txtGraTot').value = '0.00';
//entering deduction amount
var txtCredit = document.getElementById('txtCreditAmt').value;
//subtracting values
var lclRes = (parseFloat(txtGrandTotal) - parseFloat(txtCredit)).toFixed(2);
//again storing values to Textbox GrandTotal
$("#txtGraTot").val(lclRes);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtCreditAmt" oninput="credit();">
<input type="text" id="txtGraTot">
结果并不像我预期的那样。如果我在3
输入框中输入txtCredit
,则从总计中扣除的值为100 - 3 = 97
。但如果我再次输入点(。),结果为97 - . = 94
。为什么会这样?
答案 0 :(得分:0)
我不确定这是否是你想要的,但这应该是有道理的。
<强>被修改强>
添加按下输入按钮后的功能,计算并重置txtCreditAmt。
function credit(){
//subtracting values
var lclRes = (parseFloat($("#txtGraTot").val()) - parseFloat($("#txtCreditAmt").val())).toFixed(2);
//again storing values to Textbox GrandTotal
$("#txtGraTot").val(lclRes);
}
$('#txtCreditAmt').keypress(function(e){
if (e.keyCode == 13) {
credit();
$("#txtCreditAmt").val('');
return false;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtCreditAmt" onblur="credit();">
<input type="text" id="txtGraTot" value="100">
答案 1 :(得分:0)
问题是您没有将总计的原始值存储在单独的变量中。因此,当 Grand total Credit
Original state: 100 ___
Press 3 : 97 3 oninput invoked, grand total = (100 - 3)
Press . : 94 3. oninput invoked, grand total = (97 - 3.)
事件触发时,它每次都会更新总计。这是正在发生的事情:
input
快速简便(但不是理想的)解决方案是将总计的原始值存储在单独的变量中,并在每次data-total
事件触发时使用它。我的解决方案是将该值存储在$("#txtGraTot").data("total")
属性(// Save the original value of grand total in an attribute for future use.
if ($("#txtGraTot").data("total") === undefined) {
$("#txtGraTot").data("total", txtGrandTotal);
} else {
// else, get the original grand total value.
txtGrandTotal = $("#txtGraTot").data("total");
}
)中,但您可以在其中添加其他内容。只需确保从原始值中减去,而不是从文本框中的当前值中减去。
function credit(){
//storing value of grandTotal in txtGrandTotal.
var txtGrandTotal = $("#txtGraTot").val();
// Save the original value of grand total in an attribute for future use.
if ($("#txtGraTot").data("total") === undefined) {
$("#txtGraTot").data("total", txtGrandTotal);
} else {
// else, get the original grand total value.
txtGrandTotal = $("#txtGraTot").data("total");
}
//here resetting value of grandTotal to 0.00
var txtGraTotal = document.getElementById('txtGraTot').value = '0.00';
//entering deduction amount
var txtCredit = document.getElementById('txtCreditAmt').value;
//subtracting values
var lclRes = (parseFloat(txtGrandTotal) - parseFloat(txtCredit)).toFixed(2);
//again storing values to Textbox GrandTotal
$("#txtGraTot").val(lclRes);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="txtCreditAmt" oninput="credit();">
<br>
<input type="text" id="txtGraTot">
{{1}}