在文本框中仅输入数字
Enter only digits in a textbox
我使用这个函数只在文本框中输入数字并且它起作用了。
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
但客户要求我限制 -
签名,因此用户不应输入 - 签名。所以我将代码修改为:
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode == 45)
return false;
return true;
}
现在不行了,它也允许字母,为什么?
您应该在测试中使用 ||
而不是 &&
。
在我的 azerty
键盘上,-
符号字符代码是 54
,而不是 45
。
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode == 45) )
return false;
return true;
}
编辑
看起来像你的 charCode is correct。 54
值来自我的 azerty
键盘。
不过,您应该在支票中使用 ||
而不是 &&
。
你需要 ||
加入群组:
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var bool = (charCode > 31) && (charCode < 48 || charCode > 57 || String.fromCharCode(charCode) == "-");
return !bool;
}
<input type="text" onkeypress='return isNumberKey(event)'>
我使用这个函数只在文本框中输入数字并且它起作用了。
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
但客户要求我限制 -
签名,因此用户不应输入 - 签名。所以我将代码修改为:
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode == 45)
return false;
return true;
}
现在不行了,它也允许字母,为什么?
您应该在测试中使用 ||
而不是 &&
。
在我的 azerty
键盘上,-
符号字符代码是 54
,而不是 45
。
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode == 45) )
return false;
return true;
}
编辑
看起来像你的 charCode is correct。 54
值来自我的 azerty
键盘。
不过,您应该在支票中使用 ||
而不是 &&
。
你需要 ||
加入群组:
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var bool = (charCode > 31) && (charCode < 48 || charCode > 57 || String.fromCharCode(charCode) == "-");
return !bool;
}
<input type="text" onkeypress='return isNumberKey(event)'>