5

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!

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
maca
  • 480
  • 3
  • 12

1 Answers1

2

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.

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • "I believe it should complain and block the input, but for some reason does not", It doesn't block input, but it fails a validation constraint so you can apply a custom style to the field to *inform* the user that the value is invalid and let them correct it. See https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/max – haylem Oct 22 '21 at 10:11
  • @JeremyThille: I did ;) – haylem Oct 22 '21 at 10:12
  • Indeed. In other words it's very loose, and not aggressively blocking any value that exceeds the maximum. It's mainly informative – Jeremy Thille Oct 22 '21 at 10:12