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

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

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

Praveen Jeganathan报道

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


当前回答

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, ''));
});

这很简单,我们已经有一个javascript内置函数“isNaN”在那里。

$("#numeric").keydown(function(e){
  if (isNaN(String.fromCharCode(e.which))){ 
    return false; 
  }
});

上面提到的numeric()插件在Opera中不起作用(你不能退格,不能删除,甚至不能使用后退或前进键)。

下面的代码在JQuery或Javascript都可以完美地工作(它只有两行)。

JQuery:

$(document).ready(function() {
    $('.key-numeric').keypress(function(e) {
            var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
            if (verified) {e.preventDefault();}
    });
});

Javascript:

function isNumeric(e)
{
    var keynum = (!window.event) ? e.which : e.keyCode;
    return !((keynum == 8 || keynum == undefined || e.which == 0) ? null : String.fromCharCode(keynum).match(/[^0-9]/));
}

当然,这只适用于纯数字输入(加上退格键、删除键、前进/后退键),但可以很容易地更改为包含点和减号字符。

如果希望限制输入(而不是验证),可以使用键事件。就像这样:

<input type="text" class="numbersOnly" value="" />

And:

jQuery('.numbersOnly').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

这将立即让用户知道他们不能输入alpha字符等,而不是在验证阶段之后。

您仍然需要验证,因为输入可能是通过鼠标剪切和粘贴来填充的,也可能是通过表单自动补全程序填充的,这可能不会触发键事件。

我使用这个函数,它工作得很好

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