HTML 文本输入仅允许数字输入 [英] HTML text input allow only numeric input

查看:33
本文介绍了HTML 文本输入仅允许数字输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种快速的方法可以将 HTML 文本输入 (<input type=text/>) 设置为仅允许数字键击(加 '.')?

Is there a quick way to set an HTML text input (<input type=text />) to only allow numeric keystrokes (plus '.')?

推荐答案

注意:这是一个更新的答案.下面的评论指的是旧版本,它弄乱了键码.

Note: This is an updated answer. Comments below refer to an old version which messed around with keycodes.

在 JSFiddle 上自己尝试 在 JSFiddle.

您可以使用以下 setInputFilter 函数过滤文本 的输入值(支持复制+粘贴、拖放、键盘快捷键、上下文菜单操作、不可输入的键、插入符号位置、不同的键盘布局以及自 IE 9 以来的所有浏览器):

You can filter the input values of a text <input> with the following setInputFilter function (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, and all browsers since IE 9):

// Restricts input for the given textbox to the given inputFilter function.
function setInputFilter(textbox, inputFilter) {
  ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
    textbox.addEventListener(event, function() {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        this.value = "";
      }
    });
  });
}

您现在可以使用 setInputFilter 函数来安装输入过滤器:

You can now use the setInputFilter function to install an input filter:

setInputFilter(document.getElementById("myTextBox"), function(value) {
  return /^d*.?d*$/.test(value); // Allow digits and '.' only, using a RegExp
});

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

See the JSFiddle demo for more input filter examples. Also note that you still must do server side validation!

这是一个 TypeScript 版本.

Here is a TypeScript version of this.

function setInputFilter(textbox: Element, inputFilter: (value: string) => boolean): void {
    ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
        textbox.addEventListener(event, function(this: (HTMLInputElement | HTMLTextAreaElement) & {oldValue: string; oldSelectionStart: number | null, oldSelectionEnd: number | null}) {
            if (inputFilter(this.value)) {
                this.oldValue = this.value;
                this.oldSelectionStart = this.selectionStart;
                this.oldSelectionEnd = this.selectionEnd;
            } else if (Object.prototype.hasOwnProperty.call(this, 'oldValue')) {
                this.value = this.oldValue;
                if (this.oldSelectionStart !== null &&
                    this.oldSelectionEnd !== null) {
                    this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
                }
            } else {
                this.value = "";
            }
        });
    });
}

jQuery

还有一个 jQuery 版本.请参阅此答案.

HTML 5 有一个带有 的原生解决方案(请参阅 规范),但请注意浏览器支持各不相同:

HTML 5 has a native solution with <input type="number"> (see the specification), but note that browser support varies:

  • 大多数浏览器只会在提交表单时验证输入,而不会在输入时验证.
  • 大多数移动浏览器不支持stepminmax 属性.
  • Chrome(版本 71.0.3578.98)仍然允许用户在字段中输入字符 eE.另请参阅这个问题.
  • Firefox(版本 64.0)和 Edge(EdgeHTML 版本 17.17134)仍然允许用户在字段中输入任何文本.
  • Most browsers will only validate the input when submitting the form, and not when typing.
  • Most mobile browsers don't support the step, min and max attributes.
  • Chrome (version 71.0.3578.98) still allows the user to enter the characters e and E into the field. Also see this question.
  • Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter any text into the field.

自己尝试在 w3schools.com.

这篇关于HTML 文本输入仅允许数字输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆