Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

299
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda