Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace the previous user input with new input when max length is reached?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading