Basically, I have a number input field on my page, and I want users to only be able to insert 4 digits in the field. I know I can do something like this:
<input type="number" max="9999">
But the browser is going to check if the input is correct only when I press the "submit" button. What I want to do is : Let's say that the user types "1234" in the box, and after that he tries to type "1" or any other number. I want him to not be able to do that. Basically when he keeps pressing any of the buttons/letters, I want them to simply not appear in the box.
How can I achieve this?
var numberInput = document.getElementById('a');
numberInput.onkeypress = function(){
console.log(this.value.length)
if(this.value.length>3)
return false
}
<input id="a" type="number">
For making it generalised, use below code
var inputs = document.querySelectorAll('.restrictLength');
for( i in inputs){
inputs[i].onkeypress = function(){
console.log(this.id,this.value.length,this.getAttribute('data-restrict-to'));
if(this.value.length>Number(this.getAttribute('data-restrict-to'))-1)
return false
}
}
<input id="a" class="restrictLength" type="number" data-restrict-to="4"> restrict to 4
<br/>
<br/>
<input id="b" class="restrictLength" type="number" data-restrict-to="2"> restrict to 2
var specialKeys = new Array();
specialKeys.push(8); //Backspace
$(function () {
$("#a").bind("keypress", function (e) {
if(this.value.length>3){ return false}
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
return ret;
});
$("#a").bind("paste", function (e) {
return false;
});
$("#a").bind("drop", function (e) {
return false;
});
});
<input id="a" type="number">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With