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

296
Views
Don't let to write a number greater than max attribute in input

document.querySelector("#maca").addEventListener("keydown", function(e) {
  if (e.target.value > this.getAttribute("max")) {
    e.preventDefault();
  }
})
<input type="text" name="maca" placeholder="maca" id="maca" max="7">

I'm trying to stop the user from entering a number greater than the value of the max attribute. What is happening is that first the user is allowed to write a larger number then not.

How can I fix this?

Thanks a lot!

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

0

It's trickier than it looks, because even <input type="number" max="7"/> allows you to input 9 without complaining (I believe it should complain and block the input, but for some reason does not). Example below

<input type="number" max="7"/>

I came up with this little JS solution :

const max = +maca.getAttribute("max");

maca.addEventListener("keydown", function(e) {
  const typed = +e.key;
  
  if(!isNaN(typed)) e.preventDefault(); // Allow any non-number keys (backspace etc.)
  
  if ( +(e.target.value + typed) <= max) {
    maca.value += typed
  } else {
    console.log(`Number too big! Max is ${max}`)
  }
})
<input type="number" name="maca" placeholder="maca" id="maca" max="7">

This really won't allow the user to type 8 or 9. Also, you can type 1 but then you can't add another digit to type 11.

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!