Home > Back-end >  Don't let to write a number greater than max attribute in input
Don't let to write a number greater than max attribute in input

Time:10-22

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">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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!

CodePudding user response:

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"/>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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">
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

  • Related