Reputation: 2865
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?
Upvotes: 4
Views: 1003
Reputation: 1888
Sweet and simple.
<input id="a" type="text" maxLength = "4"
onkeypress='return event.charCode > 48 && event.charCode < 57'>
Note: Solution based on a community wiki : HTML Text Input allow only Numeric input
Upvotes: 1
Reputation: 69
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">
Upvotes: 2
Reputation: 481
<input type="number" id="userNumber">
<input type="submit" id="numberSubmit" onclick="CheckValid()">
<label id="warningMessage"></label>
<script>
function CheckValid(){
var number = document.getElementById("userNumber").value;
if(isNaN(number) || number.length != 4)
{
document.getElementById("warningMessage").innerHTML = "Invalid";
}
else{
document.getElementById("warningMessage").innerHTML = "Valid";
}
}
</script>
Upvotes: 1
Reputation: 5681
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
Upvotes: 5