什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
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
当前回答
你可以使用带有number()方法的Validation插件。
$("#myform").validate({
rules: {
field: {
required: true,
number: true
}
}
});
其他回答
最好的方法是在文本框失去焦点时检查它的上下文。
可以使用正则表达式检查内容是否为“数字”。
或者你也可以使用Validation插件,它基本上会自动完成。
有一个很好的jquery插件叫做jquery Mask plugin,设计用于在表单字段和html元素上做蒙版,但你也可以用它来简单地定义什么类型的数据可以在字段中输入:
$('.numeric-input').mask('0#');
现在只有数字将被允许在您的表单字段。
作为对这个建议的轻微改进,您可以使用带有number()、digits和range方法的Validation插件。例如,下面的语句确保你得到一个0到50之间的正整数:
$("#myform").validate({
rules: {
field: {
required: true,
number: true,
digits: true,
range : [0, 50]
}
}
});
我使用这个函数,它工作得很好
$(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;
}
});
});
你可以使用带有number()方法的Validation插件。
$("#myform").validate({
rules: {
field: {
required: true,
number: true
}
}
});