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


当前回答

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

其他回答

我看到过很多用javascript回答这个问题的问题,但最好的答案是使用type="number",并使用css删除旋转按钮,为什么需要这样做的大部分原因是旋转按钮在使用时不会发出更改事件。

解决方案:

HTML

<input type="number" class="input-class">

CSS

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* Firefox */
input[type=number] {
  -moz-appearance: textfield;
}
<input name="amount" type="text" value="Only number in here"/> 

<script>
    $('input[name=amount]').keyup(function(){
        $(this).val($(this).val().replace(/[^\d]/,''));
    });
</script>

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

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美元)

2个解决方案:

使用表单验证器(例如jQuery验证插件)

在输入字段的onblur事件期间(即当用户离开字段时)执行检查,使用正则表达式:

<script type="text/javascript">
function testField(field) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if (!regExpr.test(field.value)) {
      // Case of error
      field.value = "";
    }
}

</script>

<input type="text" ... onblur="testField(this);"/>

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

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