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

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

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

Praveen Jeganathan报道

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


当前回答

如果你使用的是HTML5,你就不需要花大力气去执行验证。只要用——

<input type="number" step="any" />

step属性允许小数点有效。

其他回答

你看不到字母的神奇出现和消失的关键下来。这也适用于鼠标粘贴。

$('#txtInt').bind('input propertychange', function () {
    $(this).val($(this).val().replace(/[^0-9]/g, ''));
});

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

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

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

此代码属于文本框中的字母限制,在按键事件时必须输入唯一数字验证。希望对你有所帮助

HTML标记:

<input id="txtPurchaseAmnt" style="width:103px" type="text" class="txt" maxlength="5" onkeypress="return isNumberKey(event);" />

函数onlyNumbers(key) {

        var keycode = (key.which) ? key.which : key.keyCode

        if ((keycode > 47 && keycode < 58) || (keycode == 46 || keycode == 8) || (keycode == 9 || keycode == 13) || (keycode == 37 || keycode == 39)) {

            return true;
        }
        else {
            return false;
        }
    }

您可以通过添加模式对文本输入使用HTML5验证。不需要使用regex或keyCodes手动验证。

<input type="text" pattern="[0-9.]+" />

$("input[type=text][pattern]").on("input", function () {
    if (!this.checkValidity())
        this.value = this.value.slice(0, -1);
});

对于输入[type=number]的解决方案,请参阅我的完整答案

我用了这个,效果很好。

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