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


当前回答

如果你想建议设备(可能是手机)在alpha和数值之间,你可以使用<input type="number">。

其他回答

给输入字段一个类(<input class="digit"…>)和使用jquery如下所示。

jQuery(document).ready(function () {
            jQuery('input.digit').live('input keyup',function(e){ jQuery(this).val(jQuery(this).val().replace( /[^\d]/g ,'')); });
});

上面的代码还可以禁用Ctrl+V笔画和右键单击笔画中的特殊字符。

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

我正在寻找一种阻止数字输入的方法,然后,因为我没有在答案中找到它,这段代码对我来说工作得很好。

我只需要在onkeypress事件中输入它。

如果您只需要阻止数字输入,我相信这将工作良好。

onkeypress="if(event.which &lt; 48 || event.which &gt; 57 ) if(event.which != 8) if(e.keyCode != 9) return false;"

解决这个问题的一个简单方法是实现一个jQuery函数来验证文本框中输入的字符,例如:

你的html代码:

<input class="integerInput" type="text">

和使用jQuery的js函数

$(function() {
    $('.integerInput').on('input', function() {
      this.value = this.value
        .replace(/[^\d]/g, '');// numbers and decimals only

    });
});

$(函数(){ $('.integerInput').on('input', function() { 这一点。Value = this.value .replace(/[^\d]/g, ");//只能输入数字和小数 }); }); <脚本 src = " https://code.jquery.com/jquery-2.2.4.min.js " 诚信= " sha256-BbhdlvQf / xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44 = " crossorigin =“匿名”> > < /脚本 <input type="text" class="integerInput"/>

我看到了一些很好的答案,但我喜欢它们尽可能小,尽可能简单,所以也许有人会从中受益。我将使用javascript的Number()和isNaN功能,像这样:

if(isNaN(Number(str))) {
   // ... Exception it is NOT a number
} else {
   // ... Do something you have a number
}

希望这能有所帮助。