[英]How can I get the value of 2 inputs, calculate them and put the result in another
I need to refactor this code to improve performance, I take the value of two inputs and I need to calculate them and display it in another我需要重构此代码以提高性能,我取两个输入的值,我需要计算它们并将其显示在另一个
var price;
var percentage;
var value;
function total() {
value = ((price* (percentage/ 100)) + parseFloat(price));
$("#Total").val(value.toFixed(2));
}
$("#price").keyup(function () {
price= $(this).val();
total()
});
$("#percentage").keyup(function () {
percentage= $(this).val();
total()
});
You shouldn't use global variables like this, they could cause race conditions.你不应该使用这样的全局变量,它们可能会导致竞争条件。
// this self executing function will prevent the *Field variables to be bound to your browsers' window variable.
(function() {
let priceField = $("#price");
let percentageField = $("#percentage");
let totalField = $("#Total");
function total() {
let price = priceField.val();
let percentage = percentageField.val();
let value = (price * (percentage/ 100)) + parseFloat(price);
totalField.val(value.toFixed(2));
}
priceField.keyup(function () {
total()
});
percentageField.keyup(function () {
total()
});
})()
I have to say, this is a solution for your question, but it's not the nicest one out there.我不得不说,这是您问题的解决方案,但它不是最好的解决方案。 But based on my guess, this solution needs to be simple.
但根据我的猜测,这个解决方案需要简单。
A few extra tips would be to selectively search for input fields like $("input#price")
to prevent any other potential collisions, although an id should be unique.一些额外的提示是有选择地搜索像
$("input#price")
这样的输入字段,以防止任何其他潜在的冲突,尽管 id 应该是唯一的。
I also would suggest to add some protection in the code.我还建议在代码中添加一些保护。 If anybody entered some non numeric values, what should happen.
如果有人输入了一些非数值,会发生什么。 Should they be stripped from the input before the calculations are made, or should they trigger an error to the user stating that the user's input is not valid.
是否应该在进行计算之前从输入中删除它们,或者它们是否应该向用户触发错误,指出用户的输入无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.