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


当前回答

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

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);
    }
  })
});

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

其他回答

下面的函数将检查每个输入字符是否为number。

numeric: value => {
    let numset = new Set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']);
    console.log(numset.has(value.substring(value.length - 1, value.length)));
}

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

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

有一个很好的解决方案。删除前导零,设置自然位和小数点后的最大位数,处理复制粘贴,确保它是一个数值。

this.value = this.value
    .replace(/\b0+/g, '')
    .replace(/[^0-9.]/g, '')
    .replace(/(\..*?)\..*/g, '$1')
    .replace(/([0-9]{0,6}(\.[0-9]{0,2})?).*/g, '$1')

最后替换设置小数点和自然位的长度。只需将标记替换为您喜欢的值。

.replace (/ ([0 - 9] {0, < max_natural >} (\ [0 - 9] {0, < max_decimal >}) ?)。* / g, 1美元)

这是一个简单的解决方案

取代。price-input输入。数量与输入字段的类

$(".price-input input.quantity").on("keypress keyup blur",function (event) {    
       $(this).val($(this).val().replace(/[^\d].+/, ""));
        if ((event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }
    });

ReactJS:

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