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


当前回答

这是一个改进的函数:

function validateNumber(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
    theEvent.returnValue = false;
    if (theEvent.preventDefault) theEvent.preventDefault();
  }
}

其他回答

var userName = document.querySelector('#numberField'); userName.addEventListener('input', restrictNumber); 函数限制数字(e) { var newValue = this.value.replace(new RegExp(/[^\d]/,'ig'), “”); this.value = newValue; } <输入类型=“文本” id=“数字字段”>

我找不到一个明确的答案,它不会每次都遍历整个字符串,所以这里:

document.querySelectorAll("input").forEach(input => {
  input.addEventListener("input", e => {
    if (isNaN(Number(input.value[input.value.length-1])) && input.value[input.value.length-1] != '.') {
      input.value = input.value.slice(0, -1);
    }
  })
});

没有正则表达式,它会在每次输入时检查最后一个字符,如果它不是数字或句点,它就会切片。

这是我的一句话解决方案!

$('#input-field').keypress(e => !String.fromCharCode(e.which).match(/\D/g));

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

<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');">

有一个更简单的解决方案,之前没有人提到过:

inputmode="numeric"

阅读更多信息:https://css-tricks.com/finger-friendly-numerical-inputs-with-inputmode/