Restriction on entering numbers into input

Restriction on entering numbers into input

Html

<input type="text" class="input">

Div into which we can enter data.

Js

const maxChars = 4;
const input = document.querySelector('.input');

input.addEventListener('keydown', function(){
if (this.value.length >= maxChars) {
this.value = this.value.substr(0, maxChars);
}
});

input.addEventListener('keyup', function(){
if (this.value.length >= maxChars) {
this.value = this.value.substr(0, maxChars);
}
});

The logic is as simple as possible. Set the number of characters in the variable maxChars… Then, using the events of pressing / releasing buttons, we write the functions. Inside the function, the condition is if the length of the input data is greater than or equal to maxChars – oh, we use the method substrto delete unnecessary input characters AFTER four input characters.

Leave a Reply

Your email address will not be published. Required fields are marked *