我一直很难使用keyup函数
获取两个输入值之间的精确值。首先,我得到准确的结果来计算并在另一个输入标签中显示结果,但是当我添加另一个输入标签时,它会显示错误的结果。要理解我的意思,只需检查下面的代码即可。
HTML:
<input id="ivpd" type="text" name="input_vat_per_document" placeholder="Input VAT per Document">
<input id="gta" type="text" readonly>
<input id="gp" type="text" readonly>
JS:
$('#ivpd').keyup(function(){
var percentage = 12 / 100;
var gta = $('#ivpd').val() / percentage;
var gp = $('#ivpd').val() + $('#gta').val();
if (gta == Number.POSITIVE_INFINITY || gta == Number.NEGATIVE_INFINITY || isNaN(gta))
gta = "N/A"; // OR 0
$('#gta').val(gta);
$('#gp').val(gp);
});
例如:
如果我在 ivpd
中输入 964.25
,gta
将为 8035.75
,但 gp
显示 964.298035.75
这是错误的结果。它应该是ivpd
+ gta
。
最佳答案
value
input-elements
的属性(property)总是返回 DOMString
如果任何操作数的类型为 string
, Addition(+)
运算符会做 string concatenation
操作不addition
.
Cast
input-value
toNumber
and then manipulate.
Unary plus (+)
,unary plus operator
位于其操作数之前并计算其操作数,但尝试将其转换为 number
,如果还没有的话。
注意: Number
也可以用来代替 Unary plus (+)
$('#ivpd').keyup(function() {
var percentage = 12 / 100;
var gta = +this.value / percentage;
var gp = +this.value + +$('#gta').val();
if (gta == Number.POSITIVE_INFINITY || gta == Number.NEGATIVE_INFINITY || isNaN(gta))
gta = "N/A"; // OR 0
$('#gta').val(gta);
$('#gp').val(gp);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input id="ivpd" type="text" name="input_vat_per_document" placeholder="Input VAT per Document">
<input id="gta" type="text" readonly>
<input id="gp" type="text" readonly>
关于javascript - keyup 函数自动计算结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37717129/