什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
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
当前回答
这很简单,我们已经有一个javascript内置函数“isNaN”在那里。
$("#numeric").keydown(function(e){
if (isNaN(String.fromCharCode(e.which))){
return false;
}
});
其他回答
作为对这个建议的轻微改进,您可以使用带有number()、digits和range方法的Validation插件。例如,下面的语句确保你得到一个0到50之间的正整数:
$("#myform").validate({
rules: {
field: {
required: true,
number: true,
digits: true,
range : [0, 50]
}
}
});
我用了这个,效果很好。
ini=$("#id").val();
a=0;
$("#id").keyup(function(e){
var charcode = (e.which) ? e.which : e.keyCode;
// for decimal point
if(!(charcode===190 || charcode===110))
{ // for numeric keys andcontrol keys
if (!((charcode>=33 && charcode<=57) ||
// for numpad numeric keys
(charcode>=96 && charcode<=105)
// for backspace
|| charcode==8))
{
alert("Sorry! Only numeric values allowed.");
$("#id").val(ini);
}
// to include decimal point if first one has been deleted.
if(charcode===8)
{
ini=ini.split("").reverse();
if(ini[0]==".")
a=0;
}
}
else
{
if(a==1)
{
alert("Sorry! Second decimal point not allowed.");
$("#id").val(ini);
}
a=1;
}
ini=$("#id").val();
});
find keycodes at http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
如果希望限制输入(而不是验证),可以使用键事件。就像这样:
<input type="text" class="numbersOnly" value="" />
And:
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
这将立即让用户知道他们不能输入alpha字符等,而不是在验证阶段之后。
您仍然需要验证,因为输入可能是通过鼠标剪切和粘贴来填充的,也可能是通过表单自动补全程序填充的,这可能不会触发键事件。
这是我刚刚完成的一个代码片段(使用Peter Mortensen / Keith Bentrup的一部分代码),用于对文本字段进行整数百分比验证(jQuery是必需的):
/* This validates that the value of the text box corresponds
* to a percentage expressed as an integer between 1 and 100,
* otherwise adjust the text box value for this condition is met. */
$("[id*='percent_textfield']").keyup(function(e){
if (!isNaN(parseInt(this.value,10))) {
this.value = parseInt(this.value);
} else {
this.value = 0;
}
this.value = this.value.replace(/[^0-9]/g, '');
if (parseInt(this.value,10) > 100) {
this.value = 100;
return;
}
});
这段代码:
允许使用主数字键和数字键盘。 验证以排除shift数字字符(例如#,$,%等) 将NaN值替换为0 替换为100个大于100的值
我希望这能帮助到那些需要帮助的人。
我有一段代码,它很好地完成了这项工作。
var prevVal = '';
$(".numericValue").on("input", function (evt) {
var self = $(this);
if (self.val().match(/^-?\d*(\.(?=\d*)\d*)?$/) !== null) {
prevVal = self.val()
} else {
self.val(prevVal);
}
if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57) && (evt.which != 45 && self.val().indexOf("-") == 0)) {
evt.preventDefault();
}
});