在一组旋转器中,当一个旋转器的值发生变化时,更新其他旋转器的最大值
In a group of spinners, update other spinners max value on change of a spinner value
我遇到过这样一个场景,我们有三个输入微调器,最初的最大值设置为20,现在如果任何一个微调器的值改变了,那么其他微调器的最大值也应该改变。例如:有三个spinner1, spinner2, spinner3, Max为20,如果最初spinner1被设置为3,那么spinner2和spinner3应该能够选择最大值直到17,现在是spinner2被设置为10,那么spinner3只能选择最大值7,现在如果spinner1再次被设置为1,那么spinner2和spinner3应该能够选择剩余的20-(1+10)值中的最大值
老实说,这类问题真的不适合SO。当一个人来这里寻求帮助时,我们通常期望他们自己做了合理的尝试来编写代码,但遇到了一个他们无法解决的特定问题。
我们还希望请求者展示他们遇到问题的实际代码,并能够清楚地说明他们代码的预期结果是什么,以及描述他们当前的尝试如何未能满足期望。
话是这么说的,我今天早上需要休息一下,所以请看看下面,它应该正好符合你的需要。查看代码,如果您对某些内容的工作方式有任何疑问,请随时提问:
$('.restrain').change(function(){
var $this=$(this); // cache the spinner the user interacted with
var $group=$(this).closest('.restrain-group'); // get the group that contains the spinner
var maxAllowed=$group.data('restrain-group-max'); // get the group max from the data attribute on the container
var $spinners=$.merge($group.find('.restrain').not(this), $this); // get all of the spinners for the current group, arrange the collection so that the current spinner is always last, this is VERY important
var total=0; // store our running total
$spinners.each(function(){
var $this=$(this); //cache the current spinner in the loop
var curVal=Number($this.val()); // get the current spinner's value
var newVal=total+curVal;// add the value to the running total
if(newVal>maxAllowed){ // if the running total is now higher than the maxAllowed, we've gone too high
var adjustVal=newVal-maxAllowed; // figure out how much over the total we are
var replacementVal=curVal-adjustVal; // subtract the overage from the current spinner's value
replacementVal = replacementVal <0 ? 0 :replacementVal;
$this.val(replacementVal); // set the current spinner to the lowered value
curVal=replacementVal;
}
total=total+curVal; // add the last value to the total before checking the next spinner
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="restrain-group" data-restrain-group-max="20">
<input class="restrain" type="number" min="0" step="2" value="6" size="6">
<input class="restrain" type="number" min="0" step="2" value="6" size="6">
<input class="restrain" type="number" min="0" step="2" value="6" size="6">
</div>
相关文章:
- 在Javascript数组中查找绝对最大值
- Html5输入属性的默认值,如最小值、最大值、大小等
- 按最大值获取数组索引
- 识别滑块范围的最小值和最大值
- 如何在最大值之前的某个点停止范围滑块
- 访问Highcharts系列的最小/最大值:afterSetExtremes不会激发
- 如何在拖动后获得图表的最小值和最大值放大高图表
- AngularJs:在数字输入字段中设置验证的条件最小值和最大值
- HTML5范围滑块最小值和最大值
- 如何仅在存在最小值和最大值时才显示错误消息
- 在 JavaScript 事件中添加最小值和最大值
- 从 JavaScript 中的数组中获取最大值和最小值
- 获取整数对象属性名称的最小值和最大值
- 高图表 - 在缩放重置中设置最大值和最小值
- Java 脚本 设置日期的最小值和最大值属性
- 使用javascript动态更改select中的最大值
- 如何设置jQuery微调器的最大值和最小值
- 当达到最小值和最大值时,防止在输入中显示额外的文本
- 使用函数从数组中查找最小值和最大值
- 在一组旋转器中,当一个旋转器的值发生变化时,更新其他旋转器的最大值