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

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

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

Praveen Jeganathan报道

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


当前回答

我用了这个,效果很好。

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

其他回答

只需通过parseFloat()运行内容。它将在无效输入时返回NaN。

我刚找到了一个更好的插件。 给你更多的控制。 假设您有一个DOB字段,您需要它是数字,但也接受“/”或“-”字符。

效果很好!

请登录http://itgroup.com.ph/alphanumeric/查看。

jquery。数字插件也很适合我。

我唯一不喜欢的就是直觉。在没有任何反馈的情况下,按键被“禁止”,用户可能会变得偏执或怀疑他的键盘是否坏了。

我在插件中添加了第二个回调函数,使阻塞输入的简单反馈成为可能:

$('#someInput').numeric(
    null, // default config
    null, // no validation onblur callback
    function(){
        // for every blocked keypress:
        $(this).effect("pulsate", { times:2 }, 100);
    }
);

当然,这只是一个示例(使用jQuery UI)。任何简单的视觉反馈都有帮助。

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

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

使用按键事件

数组的方法

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();
    });