我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。
我如何使用jQuery做到这一点?
当前回答
下面是使用正则表达式的方法:
$('input').bind('keypress', function (event) {
var regex = new RegExp("^[0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
https://jsfiddle.net/astrapi69/qbk2vjty/1/
你可以把正则表达式改成其他任何东西如果你想限制其他字符,然后是数字。
其他回答
为什么这么复杂?你甚至不需要jQuery,因为有一个HTML5的模式属性:
<input type="text" pattern="[0-9]*">
最酷的是它在移动设备上显示了一个数字键盘,这比使用jQuery好多了。
如果你必须解决变音符和特殊字符,尝试使用这个:
$(this).on( 'keypress', function( e )
{
// Ensure that it is a number and stop the keypress
if (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) {
e.preventDefault();
}
});
重构了已接受的答案,因此不再需要使用注释,因为我讨厌注释。这也更容易用茉莉花进行测试。
allowBackspaceDeleteTabEscapeEnterPress: function(event){
return ($.inArray(event.keyCode, [46, 8, 9, 27, 13, 190]) >= 0);
},
allowContorlAPress: function(event){
return (event.keyCode == 65 && event.ctrlKey === true)
},
allowHomeEndLeftRightPress: function(event){
return (event.keyCode >= 35 && event.keyCode <= 39)
},
theKeyPressedIsEditRelated: function (event) {
return (this.allowBackspaceDeleteTabEscapeEnterPress(event)
|| this.allowContorlAPress(event)
|| this.allowHomeEndLeftRightPress(event));
},
isNotFromTheNumKeyPad: function (event) {
return (event.keyCode < 96 || event.keyCode > 105);
},
isNotFromTopRowNumberKeys: function (event) {
return (event.keyCode < 48 || event.keyCode > 57);
},
theKeyIsNonNumeric: function (event) {
return (event.shiftKey
|| (this.isNotFromTopRowNumberKeys(event)
&& this.isNotFromTheNumKeyPad(event)));
},
bindInputValidator: function(){
$('.myinputclassselector').keydown(function (event) {
if(this.validateKeyPressEvent(event)) return false;
});
},
validateKeyPressEvent: function(event){
if(this.theKeyPressedIsEditRelated(event)){
return;
} else {
if (this.theKeyIsNonNumeric(event)) {
event.preventDefault();
}
}
}
你可以尝试HTML5数字输入:
<input type="number" value="0" min="0">
对于不兼容的浏览器,可以使用Modernizr和Webforms2。
我在我们的内部common js文件中使用了这个。我只是将类添加到需要这种行为的任何输入中。
$(".numericOnly").keypress(function (e) {
if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});