这是代码:
$(".onlynumbers").keydown(function(e) {
var isModifierkeyPressed = (e.metaKey || e.ctrlKey || e.shiftKey);
var isCursorMoveOrDeleteAction = ([46, 8, 37, 38, 39, 40].indexOf(e.keyCode) != -1);
var isNumKeyPressed = (e.keyCode >= 48 && e.keyCode <= 58) || (e.keyCode >= 96 && e.keyCode <= 105);
var vKey = 86,
cKey = 67,
aKey = 65;
switch (true) {
case isCursorMoveOrDeleteAction:
case isModifierkeyPressed == false && isNumKeyPressed:
case (e.metaKey || e.ctrlKey) && ([vKey, cKey, aKey].indexOf(e.keyCode) != -1):
break;
default:
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="enterCheckCheckNumber" maxlength="12" style="width:70%; float: right;" type="text" class="form-controlEnterCheck onlynumbers" placeholder="Check Number" />
答案 0 :(得分:0)
如前所述,问题是如果不在提及的密钥中,您将停止事件。您必须添加特殊密钥,例如Tabs
,Delete
,Caps
等,或者您可以只允许用户输入任何内容,然后在键入后清除它。
$(".onlynumbers").on("input",function(e) {
this.value = this.value.replace(/[^0-9]/g, "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="enterCheckCheckNumber" maxlength="12" style="width:70%; float: right;" type="text" class="form-controlEnterCheck onlynumbers" placeholder="Check Number" />
答案 1 :(得分:0)
var key ='哪个'在e? e.which:e.keyCode;
尝试使用这段代码。
$(".onlynumbers").keydown(function(e) {
var isModifierkeyPressed = (e.metaKey || e.ctrlKey || e.shiftKey);
var isCursorMoveOrDeleteAction = ([46, 8, 37, 38, 39, 40].indexOf(e.keyCode) != -1);
var isNumKeyPressed = (e.keyCode >= 48 && e.keyCode <= 58) || (e.keyCode >= 96 && e.keyCode <= 105);
var vKey = 86,
cKey = 67,
aKey = 65,
keycode = event.which;
switch (true) {
case isCursorMoveOrDeleteAction:
case isModifierkeyPressed == false && isNumKeyPressed:
case (e.metaKey || e.ctrlKey) && ([vKey, cKey, aKey, keycode].indexOf(e.keyCode) != -1):
break;
default:
e.preventDefault();
}
});
将输入类型更改为html中的数字。