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.metaKey === 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"