如何限制HTML5输入类型=“数字”的用户输入字符长度? [英] How to restrict user input character length of HTML5 input type="number"?
问题描述
如何在HTML5 输入[type = number]
文本框中将用户输入限制为给定长度?
How do I restrict user input to a given length in an HTML5 input[type=number]
textbox?
答案
不处理非法输入
<input class="quantity" type="number" min="0" max="99999" maxlength="5" />
$("quantity").keyup(function(){
var $field = $(this);
if ($field.val().length > Number($field.attr("maxlength"))) {
var value = $field.val().slice(0, 5);
$field.val(value);
}
});
我知道不支持maxlength属性,但我用它来获取给定的长度。
I know the maxlength attribute is not supported, but I use it to obtain the given length.
上面的代码在firefox中运行正常,但在chrome和safari中它只有在我输入五个VALID字符时才有效。当我开始输入任何无效字符时,例如a,b等,我可以输入更多字母,文本框颜色变为红色。
The above code works fine in firefox, but in chrome and safari it works only if I input five "VALID" characters. When I start typing any invalid characters, e.g. "a", "b" etc., I am able to type in more letters and the textbox color changes to red.
我发现当输入变为无效时 $ field.val()
返回空字符串, $ field.val()。length
返回 0
。
I found that when the input becomes invalid the $field.val()
returns always empty string and the $field.val().length
returns 0
.
我甚至尝试将keyCode转换为用于输入的字符并将其存储在data-value属性中用于检查和覆盖输入值的输入框但它看起来似乎不可靠。
I even tried converting the keyCode to character intended to input and store it in a "data-value" attribute to the input box to check against and overwrite the value of the input but it didn't seem to be reliable.
是否有任何解决方案可以使<$ code>输入[type = number] 行为与相同[type = text] [maxlength = 5]
?
Is there any solution with which I can make the input[type=number]
behave same as input[type=text][maxlength=5]
?
推荐答案
这是我在测试几件事后的建议
Here is my suggestion after testing a few things
- 它处理多个具有数量类别的字段
- 它处理支持的非法输入
- 通过存储所有
defaultValue来初始化
类<的字段/ li>
- 处理奇怪的问题.index()
- 适用于IE< 10 too
- 在Safari 5.1中测试在Windows上 - 它对is(:无效)作出反应,但在IE8中无效
- it handles more than one field with the quantity class
- it handles illegal input where supported
- initialises by storing all
defaultValue
s of the fields with the class - handles a weirdness with .index()
- works in IE<10 too
- tested in Safari 5.1 on Windows - it reacted to the is(":invalid") which however is invalid in IE8
var inputQuantity = [];
$(function() {
$(".quantity").each(function(i) {
inputQuantity[i]=this.defaultValue;
$(this).data("idx",i); // save this field's index to access later
});
$(".quantity").on("keyup", function (e) {
var $field = $(this),
val=this.value,
$thisIndex=parseInt($field.data("idx"),10); // retrieve the index
// NOTE :invalid pseudo selector is not valid in IE8 so MUST be last
if (this.validity && this.validity.badInput || isNaN(val) || $field.is(":invalid") ) {
this.value = inputQuantity[$thisIndex];
return;
}
if (val.length > Number($field.attr("maxlength"))) {
val=val.slice(0, 5);
$field.val(val);
}
inputQuantity[$thisIndex]=val;
});
});
这篇关于如何限制HTML5输入类型=“数字”的用户输入字符长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!