I have an input which max length = 3
#username {
width: 30px;
}
<input type="text" id="username" name="username" maxlength="3">
Is there a way to automatically replace the oldest user input with the latest user input when max length is reached?
E.g. user types ‘a’, ‘b’, ‘c’, ‘abc’ is showing in the input. If user types ‘d’, ‘bcd’ should be shown in the input.
>Solution :
You can get the last 3 characters of the input using String.prototype.substr(), then replace the input with the last 3 characters when someone inputs a value.
document.getElementById('username').addEventListener('input', function() {
this.value = this.value.substr(-3);
});
<input type="text" id="username" name="username">
You will have to remove the maxlength="3", because otherwise people don’t have the chance to input the 4th character used to rotate the string.