[英]Check if the sum of fields are greater than 100?
What I try to achieve to give alert if the sum of first values are greater than 100 if not third value has to be calculated like this; 如果第一个值的总和大于100,我试图提供警报,如果不是第三个值必须像这样计算; 3th textbox= 100- 1st textbox- 2th textbox 第3个文本框= 100-第1个文本框 - 第2个文本框
It works well at the beginning. 它在一开始就运作良好。 When I type 100 for 1st textbox then 20 for 2nd I get error then I enter 80-30 I get again alert but then third times when I enter 50-30 I again get error but actually it shouldnt give error it should write in third textbox 20 当我为第一个文本框输入100然后为第二个输入20时我得到错误然后我输入80-30我再次得到提醒然后第三次当我输入50-30我再次得到错误但实际上它不应该给出错误它应该写在第三个文本框中20
$(document).ready(function() {
// calc
jQuery("#custom-419").on("change", function() {
var vorOrt = $(this).val();
jQuery("#custom-420").on("change", function() {
var vorOrt2 = $(this).val();
var sum = 0;
sum += parseInt(vorOrt);
sum += parseInt(vorOrt2);
console.log($('#sum').val());
if (sum <= 100) {
var onWeb = 100 - vorOrt;
onWeb = onWeb - vorOrt2;
jQuery("#421").val(onWeb);
} else {
window.alert("The sum of values can not be more than 100!");
$('#custom-419').val("");
$('#custom-420').val("");
$('#custom-421').val("");
}
});
})
});
Because all the other answers contains jQuery, I though it may be helpful to provide a vanilla JavaScript solution. 因为所有其他答案都包含jQuery,所以尽管提供一个vanilla JavaScript解决方案可能会有所帮助。 Keep in mind that solution is for modern browser only! 请记住,该解决方案仅适用于现代浏览器!
function calc() { const counters = [...document.querySelectorAll('.counter')]; const total = document.querySelector('.total'); const sum = counters.reduce((a, b) => a += parseInt(b.value) || 0, 0); total.value = sum; if (sum <= 100) return; alert("The sum of values can not be more than 100!"); counters.forEach(x => x.value = ''); total.value = ''; } [].forEach.call(document.querySelectorAll('.counter'), x => x.addEventListener('keyup', calc));
<div> result has to be less then or equal 100 </div> <input class="counter" id="#custom-419" /> + <input class="counter" id="#custom-420" /> = <input class="total" id="#custom-421" disabled />
Because you didn't show us your current html, I made it simple. 因为您没有向我们展示您当前的HTML,所以我说得很简单。 So no explanation required I guess. 所以我猜不需要解释。
What happens in that JS solution is pretty straight forward. JS解决方案中发生的事情非常简单。
In the last line both input with the call counter
are getting an EventListener
to fire on keyup . 在最后一行中,使用调用counter
两个输入都将获取一个EventListener
以在keyup上触发。 You may keep the change
event instead... 你可以保留change
事件......
In the calc
function all values of the counters get parsed to int and aggregated to sum
. 在calc
函数中,计数器的所有值都被解析为int并聚合为sum
。 The rest of the code is nothing special. 其余的代码没什么特别的。
As the above solution is for modern browsers only (ES6+), here are two more for older browsers: 由于上述解决方案仅适用于现代浏览器(ES6 +),因此旧版浏览器还有两个:
function calc() {
const counters = document.querySelectorAll('.counter');
const total = document.querySelector('.total');
const sum = Array.prototype.reduce.call(counters, function(a, b) {
return a += parseInt(b.value) || 0;
}, 0);
total.value = sum;
if (sum <= 100) return;
alert("The sum of values can not be more than 100!");
Array.prototype.forEach.call(counters, function(x) {
x.value = '';
});
total.value = '';
}
Array.prototype.forEach.call(document.querySelectorAll('.counter'), function(x) {
x.addEventListener('keyup', calc);
});
I made two more function for this example to make it a bit more readable. 我为这个例子做了两个函数,使它更具可读性。
function calc() {
var counters = document.querySelectorAll('.counter');
var total = document.querySelector('.total');
var sum = getSum(counters);
total.value = sum;
if (sum <= 100) return;
alert("The sum of values can not be more than 100!");
clearCounters(counters);
total.value = '';
}
function getSum(counters) {
var result = 0;
for(var i = 0; i < counters.length; i++) {
result += parseInt(counters[i].value) || 0;
}
return result;
}
function clearCounters(counters) {
for(var i = 0; i < counters.length; i++) {
counters[i].value = '';
}
}
var _counters = document.querySelectorAll('.counter');
for(var i = 0; i < _counters.length; i++) {
_counters[i].addEventListener('keyup', calc);
}
Why nesting the 2 event functions ? 为什么嵌套2个事件函数?
Try this : 尝试这个 :
var vorOrt = 0; var vorOrt2 = 0; $(document).ready(function() { $('#custom-419').on('change', function() { vorOrt = $(this).val(); checkInputs(); }); $('#custom-420').on('change', function() { vorOrt2 = $(this).val(); checkInputs(); }); }); function checkInputs() { var sum = 0; sum += parseInt(vorOrt, 10); sum += parseInt(vorOrt2, 10); if (sum <= 100) { var onWeb = 100 - vorOrt - vorOrt2; $("#custom-421").val(onWeb); } else { window.alert('The sum of values can not be more than 100!'); $('#custom-419').val(''); $('#custom-420').val(''); $('#custom-421').val(''); } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="counter" id="custom-419" type="number" /> <input class="counter" id="custom-420" type="number" /> <input class="total" id="custom-421" type="number" />
Look at the following solution. 请看以下解决方案。 It uses jQuery's each
. 它使用each
jQuery。
What I did is attach the same function to every input by using a descriptive class name: counter
. 我所做的是使用描述性类名称将相同的函数附加到每个输入: counter
。 We can easily get all the input using the selector input.counter
and add an onchange event with only one line of code. 我们可以使用选择器input.counter
轻松获取所有输入,并仅使用一行代码添加onchange事件。
After that the generic function testIfMoreThanHundred
will iterate over all the element using each
and sum the values into a variable. 之后,泛型函数testIfMoreThanHundred
将使用each
元素迭代所有元素,并将值相加到变量中。
after that it's just a simple if
check to see if the value if more than a hundred. 之后, if
查看该值是否超过一百,那只是一个简单的问题。
$(document).ready(function() { // calc $("input.counter").on("change", testIfMoreThanHundred); }); //let's make a generic function shall we: function testIfMoreThanHundred() { var sum = 0; //get the elements and use each to iterate over them $("input.counter").each(function() { var number = parseInt($(this).val(), 10); //test if value is a number, if not use 0 if (!isNaN(number)) { sum += parseInt($(this).val(), 10); } else { sum += 0; } }); if (sum > 100) { alert("The sum can't be greater than a 100"); $("input.counter").val(""); //empty the values $("input.total").val(""); } else { $("input.total").val(100 - sum); //show value in third box } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="counter" id="custom-419" type="number" /> <input class="counter" id="custom-420" type="number" /> <input class="total" id="custom-421" type="number" />
Once change function is inside the other, which is not necessary, Also reset the value of sum
when alert is thrown 一旦更改功能在另一个内部,这是不必要的,还在重置警报时重置sum
的值
$(document).ready(function() { var sum = 0; // initializing sum function calSum(val) { sum += val; // will add the values console.log(sum) if (sum <= 100) { var onWeb = 100 - sum; $("#custom-421").val(onWeb); } else { alert("The sum of values can not be more than 100!"); $('#custom-419').val(""); $('#custom-420').val(""); $('#custom-421').val(""); sum = 0; } } $("#custom-419").on("change", function() { calSum(parseInt($(this).val(), 10)); }); $("#custom-420").on("change", function() { calSum(parseInt($(this).val(), 10)); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="custom-419"> <input type="text" id="custom-420"> <input type="text" id="custom-421">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.