javascript 输入类型编号只允许 2 个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33299639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Allow only 2 numbers on input type number
提问by brunodd
How to set a range between 0 and 99 on a input type number? I am using HTML5 attributes ( min="0" max="99"
) but it's not working and as far as I know this kind of attribute is not supported by some browsers.
如何在输入类型编号上设置 0 到 99 之间的范围?我正在使用 HTML5 属性 ( min="0" max="99"
) 但它不起作用,据我所知,某些浏览器不支持这种属性。
So I am using this script which blocks non-numerical characters but I want to limit the numbers to a max of 99 (only 2 digits). How can I do that?
所以我正在使用这个阻止非数字字符的脚本,但我想将数字限制为最多 99 个(只有 2 个数字)。我怎样才能做到这一点?
Also I want to allow users to use the keyboard to type the numbers.
另外我想允许用户使用键盘输入数字。
$(".js-number").numeric();
采纳答案by Sagi
Your example works if you remove the $(".js-number").numeric();
But you can edit the input.
maxlength attribute works on input type text, so I guess javascript validation is inevitable.
如果您删除 $(".js-number").numeric();,则您的示例有效。
但是您可以编辑输入。
maxlength 属性适用于输入类型文本,所以我想 javascript 验证是不可避免的。
<input type="number" class="js-number" min="0" max="99" value="0">
<script>
$(".js-number").bind('keydown', function(e){
var targetValue = $(this).val();
if (e.which ===8 || e.which === 13 || e.which === 37 || e.which === 39 || e.which === 46) { return; }
if (e.which > 47 && e.which < 58 && targetValue.length < 2) {
var c = String.fromCharCode(e.which);
var val = parseInt(c);
var textVal = parseInt(targetValue || "0");
var result = textVal + val;
if (result < 0 || result > 99) {
e.preventDefault();
}
if (targetValue === "0") {
$(this).val(val);
e.preventDefault();
}
}
else {
e.preventDefault();
}
});
</script>
回答by Kishore Sahasranaman
<input class="test-input" type="number" maxlength="12" />
<script>
$('.test-input').unbind('keyup change input paste').bind('keyup change input paste',function(e){
var $this = $(this);
var val = $this.val();
var valLength = val.length;
var maxCount = $this.attr('maxlength');
if(valLength>maxCount){
$this.val($this.val().substring(0,maxCount));
}
});
</script>
回答by Vijay Astound
you can set like this:
你可以这样设置:
<input type="text" class="js-number" maxlength="2">