[英]How to do an operation with keyup or input? javascript (jQuery)
I got a problem, I have two text fields, both have a value by default when open the page or reaload, values the I get from MySQL and PHP, like this:我遇到了一个问题,我有两个文本字段,当打开页面或重新加载时,默认情况下它们都有一个值,我从 MySQL 和 PHP 获得的值,如下所示:
<input type="text" id="field1" value="<?php echo $first_value; ?>" />
<input type="text" id="utility" value="<?php echo $second_value; ?>" />
And with javascript I would like to do that when I change the value of #field1
do a subtraction and show the result into #utility
.使用 javascript 我想在更改
#field1
的值时进行减法并将结果显示到#utility
。
The problem is that the result of the operation isn't correct, for example:问题是操作的结果不正确,例如:
if #field1
has 500 the first time and #utility
1041.00 and now if I change the value of #field1
with 1000 the new value for #utility
is -69.06, I guess it is doing the operation everytime that I delete or add a new number but I have no idea how to fix this, this is my javascript (jquery) code:如果
#field1
第一次有500, #field1
#utility
1041.00,现在如果我用1000 更改#field1
的值, #field1
#utility
的新值是-69.06,我猜每次我删除或添加新数字时它都会执行操作但我不知道如何解决这个问题,这是我的 javascript (jquery) 代码:
$('#field1').on('input', function() {
var difference = parseFloat($(this).val());
var utility = $('#utility').val().replace(/,/g, '');
var total = utility - difference;
if (!total) { total = 0; }
$('#utility').val(parseFloat(Math.round(total * 100) / 100).toFixed(2));
});
Your other option without adding extra fields would be to use .on('blur',function(){} )
or simply .blur(function(){})
不添加额外字段的另一种选择是使用
.on('blur',function(){} )
或简单地.blur(function(){})
This would cause the action to take place when input left the field forcing the refresh.当输入离开字段强制刷新时,这将导致操作发生。
I solved my problem by creating a new input field type hidden
with the same value of #utility
and I named it as #new_utilty
我通过创建一个
hidden
的新输入字段类型来解决我的问题,该输入字段类型具有相同的#utility
值,并将其命名为#new_utilty
$('#field1').on('input', function() {
var difference = parseFloat($(this).val());
var utility = $('#new_utility').val().replace(/,/g, '');
var total = utility - difference;
if (!total) {
total = 0;
$('#utility').val(parseFloat(Math.round(utility * 100) / 100).toFixed(2));
} else {
$('#utility').val(parseFloat(Math.round(total * 100) / 100).toFixed(2));
}
});
And this was my solution without Ajax Call这是我没有 Ajax 调用的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.