How to restrict the input field to enter only numbers/digits int and float both. Sometimes we need to allow both integer as well as float value for fields like amount, so in
No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
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();
}
}
Input box that accepts only valid int and float values.
$(function(){
$('.number-only').keypress(function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
Input box that accepts only valid int and float values.
UPDATE
The above answers are for most common use case - validating input as a number.
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();
});
});
Input box that accepts only valid int and float values.