Reputation: 17
here is my implementation
//I restrict the user to enter number only
if (isNaN(e.target.value)) {
e.target.value = e.target.value.substring(0, e.target.value.length - 1)
e.target.type = 'number'
}
// here I forced the user to enter only 8 numbers
if (e.target.value?.length > 8) {
e.target.value = e.target.value.substring(0, 8)
}
The above code works sometime sometime not. I need an alternative. is there any alternative that would be great. Thanks
Upvotes: 0
Views: 2422
Reputation: 59
Why dont you make it simpler
<input type="number" onKeyPress="if(this.value.length==8) return false;" max="99999999"/>
type ="number" are used to let the user enter a number. They include built-in validation to reject non-numerical entries. learn more here
Upvotes: 0
Reputation: 5084
You can use String's substr
method, to extract only 1st 8 characters, if length of input is greater than 8.
You also need to set max="99999999"
on input so that input doesn't go beyond 99999999
upon clicking <input>
's arrows.
let input = document.querySelector(".num");
input.addEventListener("input", ()=>{
if(input.value.length > 8){
input.value = input.value.substr(0,8);
}
});
<input type="number" max="99999999" class="num">
Upvotes: 2