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


当前回答

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

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

其他回答

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

对于喜欢说俏皮话的人。

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

:)

谢谢大家,这真的帮助了我!

我发现最好的一个对数据库非常有用。

function numonly(root){
    var reet = root.value;    
    var arr1=reet.length;      
    var ruut = reet.charAt(arr1-1);   
        if (reet.length > 0){   
        var regex = /[0-9]|\./;   
            if (!ruut.match(regex)){   
            var reet = reet.slice(0, -1);   
            $(root).val(reet);   
            }   
        }  
 }

然后添加事件处理程序:

onkeyup="numonly(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');">

只是使用jQuery的另一个变体

$(".numeric").keypress(function() {
    return (/\d/.test(String.fromCharCode(event.which) ))
});