我正在创建一个网页,其中我有一个输入文本字段,我想只允许数字字符,如(0,1,2,3,4,5…9)0-9。

我如何使用jQuery做到这一点?


当前回答

对于你正在寻找的东西来说,它可能是多余的,但我建议使用jQuery插件autonnumeric() -它很棒!

您可以只限制数字,十进制精度,最大/最小值等。

http://www.decorplanit.com/plugin/

其他回答

这似乎牢不可破。

// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
    this.value = this.value.replace(/[^0-9\.]+/g, '');
    if (this.value < 1) this.value = 0;
});

// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
    return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});

你可以使用一个简单的JavaScript正则表达式来测试纯数字字符:

/^[0-9]+$/.test(input);

如果输入是数字,则返回true,否则返回false。

或事件键码,简单使用如下:

     // Allow: backspace, delete, tab, escape, enter, ctrl+A and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
         // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) || 
         // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
             // let it happen, don't do anything
             return;
    }

    var charValue = String.fromCharCode(e.keyCode)
        , valid = /^[0-9]+$/.test(charValue);

    if (!valid) {
        e.preventDefault();
    }

你可以像这样使用on input事件:

$(document).on("input", ".numeric", function() {
    this.value = this.value.replace(/\D/g,'');
});

但是,这个代码特权是什么?

它适用于移动浏览器(keydown和keyCode有问题)。 它也适用于AJAX生成的内容,因为我们使用了“on”。 比按下键更好的性能,例如在粘贴事件上。

注:这是更新后的答案。下面的注释指的是一个老版本,混乱的关键代码。

jQuery

自己在JSFiddle上试试。

没有原生的jQuery实现,但你可以过滤文本<input>的输入值,使用以下inputFilter插件(支持复制+粘贴,拖放,键盘快捷键,上下文菜单操作,不可键入的键,插入符号位置,不同的键盘布局,有效性错误消息,以及ie9以来的所有浏览器):

// Restricts input for the set of matched elements to the given inputFilter function.
(function($) {
  $.fn.inputFilter = function(callback, errMsg) {
    return this.on("input keydown keyup mousedown mouseup select contextmenu drop focusout", function(e) {
      if (callback(this.value)) {
        // Accepted value
        if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){
          $(this).removeClass("input-error");
          this.setCustomValidity("");
        }
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        // Rejected value - restore the previous one
        $(this).addClass("input-error");
        this.setCustomValidity(errMsg);
        this.reportValidity();
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        // Rejected value - nothing to restore
        this.value = "";
      }
    });
  };
}(jQuery));

你现在可以使用inputFilter插件来安装一个输入过滤器:

$(document).ready(function() {
  $("#myTextBox").inputFilter(function(value) {
    return /^\d*$/.test(value);    // Allow digits only, using a RegExp
  },"Only digits allowed");
});

将您喜欢的样式应用于输入错误类。这里有一个建议:

.input-error{
  outline: 1px solid red;
}

有关更多输入过滤器示例,请参阅JSFiddle演示。还要注意,您仍然必须进行服务器端验证!

纯JavaScript(不含jQuery)

这实际上不需要jQuery,你也可以用纯JavaScript做同样的事情。请看这个答案。

HTML 5

HTML 5有一个本地的解决方案<input type="number">(参见规范),但请注意浏览器的支持不同:

大多数浏览器只在提交表单时验证输入,而在输入时不验证。 大多数移动浏览器不支持step、min和max属性。 Chrome(版本71.0.3578.98)仍然允许用户在字段中输入字符e和e。还有这个问题。 Firefox(版本64.0)和Edge (EdgeHTML版本17.17134)仍然允许用户在字段中输入任何文本。

自己去w3schools.com试试吧。

简短而甜蜜——即使在30多个答案之后,这一点永远不会得到太多关注;)

  $('#number_only').bind('keyup paste', function(){
        this.value = this.value.replace(/[^0-9]/g, '');
  });