什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
Praveen Jeganathan报道
不再有插件,jQuery在1.7版本中实现了自己的jQuery. isnumeric()。 参见:https://stackoverflow.com/a/20186188/66767
什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
Praveen Jeganathan报道
不再有插件,jQuery在1.7版本中实现了自己的jQuery. isnumeric()。 参见:https://stackoverflow.com/a/20186188/66767
当前回答
我刚找到了一个更好的插件。 给你更多的控制。 假设您有一个DOB字段,您需要它是数字,但也接受“/”或“-”字符。
效果很好!
请登录http://itgroup.com.ph/alphanumeric/查看。
其他回答
不再有插件,jQuery在1.7版本中实现了自己的jQuery. isnumeric()。
jQuery。isNumeric(value) 确定其参数是否为数字。
样品结果
$.isNumeric( "-10" ); // true
$.isNumeric( 16 ); // true
$.isNumeric( 0xFF ); // true
$.isNumeric( "0xFF" ); // true
$.isNumeric( "8e5" ); // true (exponential notation string)
$.isNumeric( 3.1415 ); // true
$.isNumeric( +10 ); // true
$.isNumeric( 0144 ); // true (octal integer literal)
$.isNumeric( "" ); // false
$.isNumeric({}); // false (empty object)
$.isNumeric( NaN ); // false
$.isNumeric( null ); // false
$.isNumeric( true ); // false
$.isNumeric( Infinity ); // false
$.isNumeric( undefined ); // false
下面是如何将isNumeric()与事件侦听器绑定在一起的示例
$(document).on('keyup', '.numeric-only', function(event) {
var v = this.value;
if($.isNumeric(v) === false) {
//chop off the last char entered
this.value = this.value.slice(0,-1);
}
});
/* 这是我的跨浏览器版本 如何允许只有数字(0-9)在HTML输入框使用jQuery? * /
$("#inputPrice").keydown(function(e){
var keyPressed;
if (!e) var e = window.event;
if (e.keyCode) keyPressed = e.keyCode;
else if (e.which) keyPressed = e.which;
var hasDecimalPoint = (($(this).val().split('.').length-1)>0);
if ( keyPressed == 46 || keyPressed == 8 ||((keyPressed == 190||keyPressed == 110)&&(!hasDecimalPoint && !e.shiftKey)) || keyPressed == 9 || keyPressed == 27 || keyPressed == 13 ||
// Allow: Ctrl+A
(keyPressed == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(keyPressed >= 35 && keyPressed <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (e.shiftKey || (keyPressed < 48 || keyPressed > 57) && (keyPressed < 96 || keyPressed > 105 )) {
e.preventDefault();
}
}
});
使用按键事件
数组的方法
var asciiCodeOfNumbers = [48, 49, 50, 51, 52, 53, 54, 54, 55, 56, 57]
$(".numbersOnly").keypress(function (e) {
if ($.inArray(e.which, asciiCodeOfNumbers) == -1)
e.preventDefault();
});
直接法
$(".numbersOnly").keypress(function (e) {
if (e.which < 48 || 57 < e.which)
e.preventDefault();
});
你可以使用带有number()方法的Validation插件。
$("#myform").validate({
rules: {
field: {
required: true,
number: true
}
}
});
我使用这个函数,它工作得很好
$(document).ready(function () {
$("#txt_Price").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
//if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57))
if ((e.which != 46 || $(this).val().indexOf('.') != -1) && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});