html实现input只允许输入数字的三种方法
方法一:判断键盘的keyCode
代码如下:
$(document).ready(function() {
$(\"#txtboxToFilter\").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e. Key === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don\'t do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
第二种方法:正则表达式
$(\'input[name=\"number\"]\').keyup(function(e) {
var float = parseFloat($(this).attr(\'data-float\'));
/* 2 regexp for validating integer and float inputs *****
> integer_regexp : allow numbers, but do not allow leading zeros
> float_regexp : allow numbers + only one dot sign (and only in the middle of the string), but do not allow leading zeros in the integer part
*************************************************************************/
var integer_regexp = (/[^0-9]|^0+(?!$)/g);
var float_regexp = (/[^0-9\\.]|^\\.+(?!$)|^0+(?=[0-9]+)|\\.(?=\\.|.+\\.)/g);
var regexp = (float % 1 === 0) ? integer_regexp : float_regexp;
if (regexp.test(this.value)) {
this.value = this.value.replace(regexp, \'\');
}
});
第三种方法:使用html5 type="number"
<input type=\"number\" name=\"quantity\" min=\"0\" max=\"9\"> 继续阅读与本文标签相同的文章
-
第16问:Filecoin从DSN角度解读
2026-05-14栏目: 教程
-
C/C+从零基础到精通,究竟是如何快速完成的?其实只需要这6步!
2026-05-14栏目: 教程
-
谷歌再爆重大安全漏洞!华为却成最大赢家?网友:这谁还敢用!
2026-05-14栏目: 教程
-
Excel崩溃文件如何找回
2026-05-14栏目: 教程
-
又一外国巨头宣布退出中国,关闭120家店,网友:中国钱不好赚了!
2026-05-14栏目: 教程
