Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
Input field allows 6 characters when there is 5 max allowed

I have a function that removes numbers from string, it also should allow for max 5 letters to be entered. When I enter 5, and then another letter or number I can see it in console log, how can I avoid this?

document.getElementById("test").addEventListener("input", (e) => {
    console.log(e.target.value);
     let temp = e.target.value.replace(/[0-9]/g, '');
     e.target.value = temp.substr(0, 5);
})
<input id="test" type="text">

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You are loggging the value before removing the excess chars. Just move your console.log to the end of the function.

document.getElementById("test").addEventListener("input", (e) => {
     let temp = e.target.value.replace(/[0-9]/g, '');
     e.target.value = temp.substr(0, 5);
    console.log(e.target.value);
})
<input id="test" type="text">

about 4 years ago · Juan Pablo Isaza Report

0

The problem with your code is that you are reading it from the current target that allows any number of characters, and later you are setting the substring from 0 to 5 on its value.

The simple fix would be to ask HTML to limit the number of characters so that the 6th character is never allowed.

This can be achieved by maxlength property.

<input id="test" type="text" maxlength="5">

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!