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


当前回答

解决这个问题的一个简单方法是实现一个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"/>

其他回答

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

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

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

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

jQuery的另一个简单方法:

$('.Numeric').bind('keydown',function(e){
    if (e.which < 48 || e.which > 57)
        return false;
    return true;
})

现在只需将每个输入类设置为Numeric,如下所示:

<input type="text" id="inp2" name="inp2" class='Numeric' />
<input name="amount" type="text" value="Only number in here"/> 

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

对于喜欢说俏皮话的人。

string.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');

我在输入type="text"上使用这段代码,并使用AngularJS在按键时激活,但如果喜欢,可以使用jQuery。只需将此代码放入一个函数中,该函数以某种方式通过按键激活。

它只允许数字,数字+十进制,数字+十进制+数字。

CODE

YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');

testOne = "kjlsgjkl983724658.346.326.326..36.346"
=> "983724658.34";

testTwo = ".....346...3246..364.3.64.2346......"
=> "346.";

testThree = "slfdkjghsf)_(*(&^&*%^&%$%$%^KJHKJHKJKJH3"
=> "3";

testFour = "622632463.23464236326324363"
=> "622632463.23";

这是为美国货币构建的,但它可以更改为允许超过两个小数点后的第一个小数,如下所示…

改变了代码

YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d*)(.*)/, '$1');

testFour = "dfskj345346346.36424362jglkjsg....."
=> "345346346.36424362";

:)

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

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