Limit Input to a Range of Values

2

I am creating a small shop that will sell shirts for an event and the sale of the 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 defined is limited to 4.

With the input type number I can set this value but if the person types the value instead of using the control created by the field it can easily add a larger 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

    
asked by anonymous 18.04.2015 / 18:05

2 answers

5

No Javascript required:

<input type='number' value='1' min='1' max='4'/>

Even if the user types any value within the input that exceeds the defined range , it will be warned and the form will not be sent until the values are correct.

You can test here (assigning any value below 1 or above 4)

Mozilla Firefox

GoogleChrome

Internet Explorer

    
18.04.2015 / 18:22
3

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

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