Limit number on an input

Asked

Viewed 67 times

0

I would like to know how to limit the maximum number entered in an input. For example: I want the largest number that can be typed to be 42, that is, if the user tries to type 43: either it would appear only the four, or, when typing the 4, it would display the 2, because the limit is 42, and the minimum is 1.

The result doesn’t necessarily have to be the one I mentioned, I just need her not to be able to type the number 43 onwards. If possible she can’t even using CTRL + V kkk, but any progress already helps me, follow the code I’m currently using with the same example, but it’s not working.

<input type="number" min="1" max="42">
  • Is your field in a form? Inside a <form>.

2 answers

2


This feature of typing the 4 appear the 2 can be dispensable as the user may intend to type 41 and this will mess instead of helping.

But you can change the value of the field to the minimum if a value less than the min, or to the maximum value if you try to enter a value greater than the max.

You can use the event oninput and call a function by passing the element as a parameter with this. The oninput detects any change in the field, even by pasting.

It would also be interesting to already start the field with the minimum value by placing the attribute value="1":

function checa(e){
   const mi = +e.min;
   const ma = +e.max;
   const va = e.value;
   if(va < mi){
      e.value = mi;
   }else if(va > ma){
      e.value = ma;
   }
}
<input oninput="checa(this)" value="1" type="number" min="1" max="43">

  • Thanks Sam! That’s the way I wanted it! I had already found a function, but as I was inside a table I was having some problems, but its worked exactly to other function, but without problems. Hug.

0

What if the maximum value is 10, and I need to type, for example: the number 6? I cannot.

function checa(e){
   const mi = +e.min;
   const ma = +e.max;
   const va = e.value;
   if(va < mi){
      e.value = mi;
   }else if(va > ma){
      e.value = ma;
   }
}
<input oninput="checa(this)" value="1" type="number" min="1" max="10">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.