如何限制输入字段只输入数字/数字 int 和 float 两者。 有时我们需要为金额等字段同时允许整数和浮点值,因此在这种情况下需要进行验证。没有可用的解决方案,但它们的代码量很大。所以需要一个简短但有效的代码。
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
最佳答案
No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
Javascript 方法
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
jQuery 方法
$(function(){
$('.number-only').keypress(function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
更新
以上答案适用于最常见的用例 - 将输入验证为数字。
But as per comments, some wants to allow few special cases like negative numbers & showing the invalid keystrokes to user before removing it, so below is the code snippet for such special use cases.
$(function(){
$('.number-only').keyup(function(e) {
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
.split('').reverse().join('');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
关于javascript - 输入数字验证 - 限制仅输入数字或数字,int 和 float 两者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30287531/