我的输入字段限制为3个字符,我只想允许数字
我的解决方案几乎适用于所有情况:(下面的问题)
// Avoid any unwanted keys from showing
$("input#test").keypress(function(event) {
if (!isApprovedKeyCode(event)) {
event.preventDefault();
event.stopImmediatePropagation();
}
});
// Useless try to prevent accents from showing
$("input#test").keydown(function(event) {
if (event.keyCode == 229) { // ´
event.preventDefault();
event.stopImmediatePropagation();
event.stopPropagation();
return false;
}
});
//A few character modifiers (i.e. ´`¨^~) do not trigger keypress
//This ensures the input only contains numbers
$("input#test").keyup(function(event) {
var element = event.target;
var validString = element.value.replace(/[^0-9]/g, '');
if (validString !== element.value) {
element.value = validString;
}
});
function isApprovedKeyCode(event) {
var keyCode = event.which || event.keyCode;
var character = String.fromCharCode(keyCode);
return isValidDigit(character);
}
function isValidDigit(character) {
var result = /\d/.test(character);
return result;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" maxlength="3" id="test" />
问题:
正如你所看到的那样,我试图在keydown中阻止这种情况,但是没有一个事件预防尝试使用这些键
我也尝试使用type =“number”的输入。快速举例:
// Limit lenght
$("input#test").keydown(function(event) {
var element = event.target;
if(element.value.length > 2) {
event.preventDefault();
event.stopImmediatePropagation();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" min="1" max="999" id="test" />
这也显示重音并允许通过按下重音符号后加数字来增加超过限制
有关正确解决方案的想法吗?
谢谢!