我试图用计数规则创建数字输入,例如,我想让前5个增量步骤为100个单位(100 - 500),一旦达到500,将增量步骤更改为500
。
所以是100, 200, 300, 400, 500, 1000, 1500, 2000...
这是我到目前为止所尝试的,某些东西只在达到600而不是500时导致500步属性触发。
$('input#grams_quantity').on( "change", function(){
console.log('works');
if($(this).val() > 400){
$("#grams_quantity").attr('step', 500);
console.log('500');
} else {
$("#grams_quantity").attr('step', 100);
console.log('100');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" step="100" name="grams_quantity" class="grams_quantity" id="grams_quantity" value="100" min="100">
如何设置规则来正确编号输入增量步骤?
获得想要的值有点棘手,因为更改发生在事件调用之前,然后它需要为下一次单击采取行动。
-
为什么不简单地改变增量为
500
工作?由于
min
值和500
的倍数。有了min="100"
和step="500"
,下一个可达的值是600
。解决方案:同时更改
min="0"
和step="500"
的值。 -
为什么我们需要另一个条件?为什么不直接检查
500
的值是否返回到step="100"
呢?-
大于
500
的解决方案:- 调整起始为0,步进为
500
。 - 调整
value
至少为1000
。
- 调整起始为0,步进为
-
小于等于
500
的解。- 调整起始为
100
,步进为500
。
- 调整起始为
-
你还需要覆盖用户输入并调整值
-
编辑:在闭包中添加last
以区分箭头更改值和手动输入值
例如,直接输入600
,该值四舍五入为500
,但如果通过向上箭头键达到该值,则得到1000
。
$('input#grams_quantity').on("change", function (last) {
return function() {
if (+$(this).val() > 500) {
$("#grams_quantity").attr('step', 500);
$("#grams_quantity").attr('min', 0);
this.value = last === 500 && +this.value === 600
? 1000
: Math.round(this.value / 500) * 500;
} else {
$("#grams_quantity").attr('step', 100);
$("#grams_quantity").attr('min', 100);
this.value = Math.max(100, Math.round(this.value / 100) * 100);
}
last = +this.value;
};
}(0));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" step="100" name="grams_quantity" class="grams_quantity" id="grams_quantity" value="100" min="100">