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

查看:113
本文介绍了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.

下面的setInputFilter函数允许您在文本<input>上使用任何类型的输入过滤器,包括各种数字过滤器(见下文).

The setInputFilter function below allows you to use any kind of input filter on a text <input>, including various numeric filters (see below).

与大多数其他解决方案不同,此正确支持:复制+粘贴,拖动+拖放,所有键盘快捷键,所有上下文菜单操作,所有不可键入的键(例如,光标和导航键),插入符号位置,所有语言和平台的所有键盘布局,以及自IE 9以来的所有浏览器.

Unlike most other solutions, this correctly supports Copy+Paste, Drag+Drop, all keyboard shortcuts, all context menu operations, all non-typeable keys (e.g. cursor and navigation keys), the caret position, all keyboard layouts of all languages and platforms, and all browsers since IE 9.

自己尝试一下在JSFiddle上.

Try it yourself on JSFiddle.

// Restricts input for the given textbox to the given inputFilter.
function setInputFilter(textbox, inputFilter) {
  ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
    textbox.oldValue = "";
    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);
      }
    });
  });
}

// Restrict input to digits and '.' by using a regular expression filter.
setInputFilter(document.getElementById("myTextBox"), function(value) {
  return /^\d*\.?\d*$/.test(value);
});

您可能要使用一些输入过滤器:

Some input filters you might want to use:

  • 整数值(仅正值):
    /^\d*$/.test(value)
  • 整数值(正值和特定上限):
    /^\d*$/.test(value) && (value === "" || parseInt(value) <= 500)
  • 整数值(正值和负值):
    /^-?\d*$/.test(value)
  • 浮点数值(允许同时使用.,作为小数点分隔符):
    /^-?\d*[.,]?\d*$/.test(value)
  • 货币值(即最多两位小数):
    /^-?\d*[.,]?\d{0,2}$/.test(value)
  • A-Z (即基本拉丁字母):
    /^[a-z]*$/i.test(value)
  • 拉丁字母(即英语和大多数欧洲语言,请参见 https://unicode-table .com 了解有关Unicode字符范围的详细信息):
    /^[a-z\u00c0-\u024f]*$/i.test(value)
  • 十六进制值:
    /^[0-9a-f]*$/i.test(value)
  • Integer values (positive only):
    /^\d*$/.test(value)
  • Integer values (positive and up to a particular limit):
    /^\d*$/.test(value) && (value === "" || parseInt(value) <= 500)
  • Integer values (both positive and negative):
    /^-?\d*$/.test(value)
  • Floating point values (allowing both . and , as decimal separator):
    /^-?\d*[.,]?\d*$/.test(value)
  • Currency values (i.e. at most two decimal places):
    /^-?\d*[.,]?\d{0,2}$/.test(value)
  • A-Z only (i.e. basic Latin letters):
    /^[a-z]*$/i.test(value)
  • Latin letters only (i.e. English and most European languages, see https://unicode-table.com for details about Unicode character ranges):
    /^[a-z\u00c0-\u024f]*$/i.test(value)
  • Hexadecimal values:
    /^[0-9a-f]*$/i.test(value)

请注意,您仍然必须进行服务器端验证!

Note that you still must do server side validation!

还有一个jQuery版本.请参见此答案或自己尝试一下在JSFiddle上.

There is also a jQuery version of this. See this answer or try it yourself on JSFiddle.

HTML 5具有使用<input type="number">的本机解决方案(请参见

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

  • 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上

Try it yourself on w3schools.com.

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

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