有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?


当前回答

我选择使用这里提到的两个答案的组合,即。

<输入类型=“编号”/>

and

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    return !(charCode > 31 && (charCode < 48 || charCode > 57));
}

<input type=“text” onkeypress=“return isNumberKey(event);”>

其他回答

在任何击键上执行此函数,它将不允许除加号、连字符和圆括号之外的任何内容。

假设:+234-(123)1231231将工作 但不是信件

替换(/ ^[0 - 9 +()——]*美元/ test (char))与(/ ^[0 - 9]*美元/ test (char))只允许数字按键。

isNumber(e) {
    let char = String.fromCharCode(e.keyCode);
    if (/^[0-9+()-]*$/.test(char)) return true;
    else e.preventDefault();
},

现在大多数浏览器都支持type="number"这个属性

<input type="number" maxlength="3" ng-bind="first">

ReactJS:

<input
    onKeyPress={(event) => {
        if (!/[0-9]/.test(event.key)) {
            event.preventDefault();
        }
    }}
/>

再举一个例子,你可以在输入字段中只添加数字,不能添加字母

<input type="text" class="form-control" id="phone" name="phone" placeholder="PHONE" spellcheck="false" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">

上面的一些答案使用了过时的内容,比如which的使用。

要检查按下的键是否为数字,可以使用keyup eventListener来读取event.key的值。如果不是数字,就不要输入字符。您可以将其他密钥加入白名单。例如,允许用户使用箭头在输入字段中向后或向前导航,或者按退格键并删除输入的数字。

validate (event) {
  const isNumber = isFinite(event.key)
  const whitelist = ['Backspace','Delete','ArrowDown','ArrowUp','ArrowRight','ArrowLeft']
  const whitelistKey = whitelist.includes(event.key)

  if (!isNumber && !whitelistKey) {
    event.preventDefault()
  }
}