[英]Jquery input number in multiples (keyup)
How can I make an input
element accept numbers only in multiples of 50? 如何使input
元素仅接受50的倍数的数字?
I know we can specify step="50"
as an attribute, but I would prefer a solution that is triggered by the keyup
event . 我知道我们可以将step="50"
指定为属性,但是我希望使用keyup
事件触发的解决方案。
I found this code, which prevents users from entering a number less than 50. 我找到了此代码,该代码可防止用户输入小于50的数字。
Question : How can I adjust this code so that only multiples of 50 can be entered ? 问题:如何调整此代码,以便只能输入50的倍数?
$('#numberbox').keyup(function(){ if ($(this).val() < 50){ alert("Minimum Quantity: 50"); $(this).val('50'); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="numberbox" type='number'>
Use the modulo operator 使用模运算符
var multiple = 50;
$('#numberbox').keyup(function(){
if (parseInt($(this).val()) % multiple ) {
alert("Only multiples of " + multiple + " allowed");
$(this).val(multiple);
}
});
You can use Remainder (%) to do this, check the example bellow. 您可以使用余数(%)进行此操作,请检查以下示例。
The remainder operator returns the remainder left over when one operand is divided by a second operand. 当一个操作数除以第二个操作数时,余数运算符返回剩余的余数。 It always takes the sign of the dividend, not the divisor. 它总是采用股息的符号,而不是除数。
$('#numberbox').keyup(function(){ if ($(this).val()%50==0){ $('#result').text($(this).val()+' is multiple of 50'); }else{ $('#result').text($(this).val()+' is not a multiple of 50'); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="numberbox" type='number'> <span id='result'></span>
Hope this helps. 希望这可以帮助。
I would prefer blur
instead of keyup
as keyup
would keep on alerting. 我更喜欢blur
而不是keyup
因为keyup
会不断keyup
警报。 To know if it is multiple of 50
check a condition with modulo
ie %
like if parseInt($(this).val())%50 != 0
要知道它是否是50
倍数,请使用modulo
即%
检查条件,例如是否parseInt($(this).val())%50 != 0
$('#numberbox').blur(function(){ if (parseInt($(this).val())%50 != 0){ alert("Multiples of 50 should be entered"); $(this).val('50'); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="numberbox" type='number'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.