Limit Input to a range of values

Asked

Viewed 3,174 times

2

I am creating a small shop that will sell shirts of an event and the sale of shirts will be limited to a maximum of 4 shirts per person, so I need that in the field where the number of shirts that the person wants to buy is set to 4.

With input type number I can set this value but if one type the value instead of using the control created by the field it can easily add a higher value.

How do I make the field only accept values 1, 2, 3 or 4 remembering that the minimum value is 1 and the maximum is 4

2 answers

6


No need for Javascript:

<form action='#'>
  <input type='number' value='20' min='1' max='4'/>
  <button type='submit'>Enviar</button>
</form>

  • I tested this but it does not work as I explained, try to put the value by hand without using the field arrows, you can easily put a value out of specified (9 for example)

  • 1

    @Darkmedia But the form is not sent if the input is invalid. You can test here putting a value above 4 and trying to send.

3

Try to bind the onchange event to a javascript function that will check the input field change and whenever it is changed check the input field value, something like this:

$("#caixa_texto").bind('input propertychange', function(){
    if($(this).val() > 4){
         $(this).val() = 4;
    }else if($(this).val() < 1){
         $(this).val() = 1;
    }
});

Browser other questions tagged

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