什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
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
当前回答
在这里找到了一个很好的解决方案http://ajax911.com/numbers-numeric-field-jquery/
我只是按照我的要求把“键上”改为“键下”
其他回答
也允许负数
下面的代码也接受负数
HTML
<input type="text" name="myText" />
JS
var pastValue, pastSelectionStart, pastSelectionEnd;
$("input").on("keydown", function() {
pastValue = this.value;
pastSelectionStart = this.selectionStart;
pastSelectionEnd = this.selectionEnd;
}).on("input propertychange", function() {
if ( this.value.length > 0 && $.isNumeric(this.value) == false && this.value != '-' ) {
this.value = pastValue;
this.selectionStart = pastSelectionStart;
this.selectionEnd = pastSelectionEnd;
}
}).on('blur', function(){
if(this.value == '-')
this.value = '';
});
我使用这个函数,它工作得很好
$(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;
}
});
});
戴夫·亚伦·史密斯,谢谢你的帖子
我编辑了你的答案,接受小数点和数字的数字部分。这个工作非常适合我。
$(".numeric").keypress(function(event) {
// Backspace, tab, enter, end, home, left, right,decimal(.)in number part, decimal(.) in alphabet
// We don't support the del key in Opera because del == . == 46.
var controlKeys = [8, 9, 13, 35, 36, 37, 39,110,190];
// IE doesn't support indexOf
var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
// Some browsers just don't raise events for control keys. Easy.
// e.g. Safari backspace.
if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
(49 <= event.which && event.which <= 57) || // Always 1 through 9
(96 <= event.which && event.which <= 106) || // Always 1 through 9 from number section
(48 == event.which && $(this).attr("value")) || // No 0 first digit
(96 == event.which && $(this).attr("value")) || // No 0 first digit from number section
isControlKey) { // Opera assigns values for control keys.
return;
} else {
event.preventDefault();
}
});
你可以使用来自decorplanit.com的autoNumeric。它们对数字、货币、舍入等都有很好的支持。
我曾经在IE6环境下使用过,只做了一些css调整,结果还算成功。
例如,可以定义一个css类numericInput,它可以用来用数字输入掩码装饰字段。
改编自autoNumeric网站:
$('input.numericInput').autoNumeric({aSep: '.', aDec: ','}); // very flexible!
最好的方法是在文本框失去焦点时检查它的上下文。
可以使用正则表达式检查内容是否为“数字”。
或者你也可以使用Validation插件,它基本上会自动完成。