我想在没有额外插件的情况下使用 jquery/javascript 在文本框中只允许数字
我的代码如下:
if ( event.keyCode == 46 || event.keyCode == 8 || (event.keyCode >=48 && event.keyCode <=57)) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
event.preventDefault();
}
但它允许特殊字符,如 ! (Shift+1)、@(shift+2)等
任何人都可以告诉我完整的解决方案吗..提前致谢
最佳答案
这是牢不可破的。
// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
this.value = this.value.replace(/[^0-9]+/g, '');
if (this.value < 1) this.value = 0;
});
// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});
关于javascript - 在没有额外插件的情况下使用 jquery 仅允许文本框中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8635381/