一起设置三个输入数字的最大值 [英] Set max value of three input numbers together
本文介绍了一起设置三个输入数字的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有三个输入数字:
<input min="0" name="cat1" step="1" type="number" max="50" value="0" />
<input min="0" name="cat2" step="1" type="number" max="50" value="0" />
<input min="0" name="cat3" step="1" type="number" max="50" value="0" />
当前最大值为50.我希望所有三个值的最大值也都为50.
Currently the max value is 50. I would like the max for all three together to be 50 aswell.
如何使用javascript或jquery解决此问题?
How can I solve this with javascript or jquery?
推荐答案
此方法对其他输入求和,如果sum +当前值大于max,它将更改当前输入的值以适合max.
This method sums the other inputs, and if the sum + the current value is greater than max, it changes the current input's value to fit max.
例如,尝试在输入框中输入30、5、20.
For example, try entering 30, 5, 20 to the input boxes.
var max = 50;
var $inputs = $('input');
function sumInputs($inputs) {
var sum = 0;
$inputs.each(function() {
sum += parseInt($(this).val(), 0);
});
return sum;
}
$inputs.on('input', function(e) {
var $this = $(this);
var sum = sumInputs($inputs.not(function(i, el) {
return el === e.target;
}));
var value = parseInt($this.val(), 10) || 0;
if(sum + value > max) $this.val(max - sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input min="0" name="cat1" step="1" type="number" max="50" value="0" />
<input min="0" name="cat2" step="1" type="number" max="50" value="0" />
<input min="0" name="cat3" step="1" type="number" max="50" value="0" />
这篇关于一起设置三个输入数字的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文