什么是限制“数字”仅输入文本框的最佳方法?
我在找一些允许小数点的东西。
我看到很多这样的例子。但还没决定用哪一种。
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
当前回答
检查数据库使用的查找代码:
function numonly(root){
>>var reet = root.value;
var arr1 = reet.length;
var ruut = reet.charAt(arr1-1);
>>>if (reet.length > 0){
var regex = /[0-9]|\./;
if (!ruut.match(regex)){
var reet = reet.slice(0, -1);
$(root).val(reet);
>>>>}
}
}
//Then use the even handler onkeyup='numonly(this)'
其他回答
你可以使用带有number()方法的Validation插件。
$("#myform").validate({
rules: {
field: {
required: true,
number: true
}
}
});
请在脚本底部添加:
if(this.value.length == 1 && this.value == 0)
this.value = "";
我用了这个,效果很好。
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
使用按键事件
数组的方法
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();
});
这个函数做同样的事情,使用上面的一些想法。
$field.keyup(function(){
var val = $j(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2) val =val.replace(/\.+$/,"");
}
$j(this).val(val);
});
显示视觉反馈(出现错误字母后消失) 允许小数 捕获多个”。 没有问题的左/右del等。