
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 substr
to delete unnecessary input characters AFTER four input characters.