如何使用 jQuery 在 HTML 输入框中只允许数字(0-9)?

新手上路,请多包涵

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

我怎样才能使用 jQuery 做到这一点?

原文由 djmzfKnm 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 329
2 个回答

注意: 这是一个更新的答案。下面的评论指的是一个乱七八糟的旧版本。

查询

在 JSFiddle 上 自己尝试。

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

 // 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"> (参见 规范),但请注意浏览器支持各不相同:

  • 大多数浏览器只会在提交表单时验证输入,而不是在键入时验证输入。
  • 大多数移动浏览器 不支持 stepminmax 属性。
  • Chrome(版本 71.0.3578.98)仍然允许用户在字段中输入字符 eE 。另见 这个问题
  • Firefox(版本 64.0)和 Edge(EdgeHTML 版本 17.17134)仍然允许用户在字段中输入 任何 文本。

在 w3schools.com 上 亲自尝试。

原文由 kgiannakakis 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是我使用的功能:

 // Numeric only control handler
jQuery.fn.ForceNumericOnly =
function()
{
    return this.each(function()
    {
        $(this).keydown(function(e)
        {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
            // home, end, period, and numpad decimal
            return (
                key == 8 ||
                key == 9 ||
                key == 13 ||
                key == 46 ||
                key == 110 ||
                key == 190 ||
                (key >= 35 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        });
    });
};

然后,您可以通过执行以下操作将其附加到您的控件:

 $("#yourTextBoxName").ForceNumericOnly();

原文由 Kelsey 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题