gpt4 book ai didi

javascript - 平衡jquery中的两个输入数字字段

转载 作者:行者123 更新时间:2023-12-02 14:17:22 25 4
gpt4 key购买 nike

我想使用 jquery 根据为两个输入数字字段设置的最大值来平衡两个输入数字字段。例如,它就像一个天平,如果一侧下降,另一侧就会上升,反之亦然。另一个例子,如果最大值为 20,那么如果我在输入字段一中输入 5,则输入字段二中将留下 15。需要帮助谢谢。尚未开始编码,但仍试图弄清楚它。

最佳答案

首先,您需要将输入事件处理程序附加到所有相关的输入字段上。该事件处理程序会将输入字段的当前输入值与总计/最大值变量进行比较,并相应地找到余数。然后,事件处理程序找到其他输入字段并为它们分配适当的余数值。

Note: This allows you to add as many inputs as you want and it will balance them all out. Just remember to add the balance class on the input field.

var total = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
this.value = value = 0;
} else if (value > total) {
this.value = value = total;
}/* else if (value < 0) {
this.value = value = 0;
}
* Remove this comment if value shouldn't be negative.
*/
var remainder = total - value;
var otherInputs = $('.balance');
otherInputs.splice($.inArray(this,otherInputs),1);
var remainderDiv = remainder/otherInputs.length;
$.each(otherInputs, function(input) {
otherInputs[input].value = remainderDiv;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">

更新:两个输入可以小于最大值,但不能高于最大值。

var max = 20;
$('.balance').on('input', function() {
var value = parseInt(this.value);
if (isNaN(value)) {
value = 0;
}
var otherInputs = $('.balance');
var sum = 0;
$.each(otherInputs, function(input) {
sum += parseInt(otherInputs[input].value);
});
if (sum > max)
this.value = max - (sum - value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="balance">
<input type="number" class="balance">

关于javascript - 平衡jquery中的两个输入数字字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38924104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com