什么是限制“数字”仅输入文本框的最佳方法?

我在找一些允许小数点的东西。

我看到很多这样的例子。但还没决定用哪一种。

Praveen Jeganathan报道

不再有插件,jQuery在1.7版本中实现了自己的jQuery. isnumeric()。 参见:https://stackoverflow.com/a/20186188/66767


当前回答

在这里找到了一个很好的解决方案http://ajax911.com/numbers-numeric-field-jquery/

我只是按照我的要求把“键上”改为“键下”

其他回答

根据CanIUse的数据,截至2015年10月,HTML5支持输入类型数字,全球浏览器的支持度高达88%以上。

<input type="number" step="0.01" min="0" name="askedPrice" id="askedPrice" />

这不是JQuery相关的解决方案,但优点是在手机上的Android键盘会对输入数字进行优化。

或者,也可以使用带有新参数"pattern"的输入类型文本。更多细节在HTML5规范。

我认为它比jquery解决方案更好,因为在这个问题中提供的jquery解决方案不支持千位分隔符。如果你能使用html5。

JSFiddle: https://jsfiddle.net/p1ue8qxj/

你可以使用带有number()方法的Validation插件。

$("#myform").validate({
  rules: {
    field: {
      required: true,
      number: true
    }
  }
});

我用了这个,效果很好。

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

最好的方法是在文本框失去焦点时检查它的上下文。

可以使用正则表达式检查内容是否为“数字”。

或者你也可以使用Validation插件,它基本上会自动完成。

我使用了James Nelli的答案,并添加了onpaste="return false;"(Håvard Geithus)以确保输入中只输入整数。即使你尝试粘贴,它也不会允许。