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


当前回答

ReactJS:

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

其他回答

<input name="amount" type="text" value="Only number in here"/> 

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

我可能有另一个(简单的)解决办法…

因为String.fromCharCode(key)在QWERTY键盘上返回奇怪的东西(数字键盘返回代码为g表示1,1表示&字符..

我已经意识到,在输入中捕获keyup的最终值,将其重置为任意值是一个更简单,轻量级和防bug的方法(也可以通过一些regex…为了保持小数等等……不需要过滤其他Ctrl, Home, Del和Enter事件…)

使用jq:

<input class='pn'>
<script>
function pn(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}
jQuery('.pn').keyup(function(){pn(this);});
</script>

Onkeyup属性:

<input onkeyup='positiveNumericInput(this)'>
<script>function positiveNumericInput(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}</script>

你也可以比较输入值(默认情况下被视为字符串)和它本身被强制为数字,比如:

if(event.target.value == event.target.value * 1) {
    // returns true if input value is numeric string
}

然而,你需要绑定到事件,如keyup等。

这也适用于波斯和阿拉伯数字:)

 setNumericInput: function (event) {
          var key = window.event ? event.keyCode : event.which
          if (event.keyCode === 8 ||
        (key >= 48 && key <= 57) ||
        (key >= 1776 && key <= 1785)) {
            return true
          } else {
            event.preventDefault()
          }
        }

这可以立即删除任何坏字符,只允许一个点,是短的,并允许退格等:

$('.numberInput').keyup(function () {
    s=$(this).val();
    if (!/^\d*\.?\d*$/.test(s)) $(this).val(s.substr(0,s.length-1));
});