Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict input type="number" to its min or max if it is out of range

I have the below code

<form:input type="number" min="1" max="4" size="5" value="1" path="n" name='n' placeholder="<5" style="height:25px;width:60px"></form:input>

if a user enters a value in the textbox out of range then it should reset to its nearest min or max value, for example if user enters in textbox as less than 1 then it should get reset to 1, if he enters more than 4 then it should get reset to 4.

Please advice if we have any other tag instead of using input tag to restrict

There is a solution already which is not working for me

like image 389
Joshi Avatar asked Apr 01 '16 06:04

Joshi


2 Answers

This solution might be what you're after: jquery: set min max input in option type number

$(function () {
    $( "input" ).change(function() {
        var max = parseInt($(this).attr('max'));
        var min = parseInt($(this).attr('min'));
        if ($(this).val() > max)
        {
            $(this).val(max);
        }
        else if ($(this).val() < min)
        {
            $(this).val(min);
        } 
    });      
}); 

@Caspian also provided a working fiddle: http://jsfiddle.net/Ddk67/75/

like image 178
Aaron Lavers Avatar answered Oct 19 '22 09:10

Aaron Lavers


It would be nice if HTML5 actually prevented values from being entered because preventing the value from being submitted only, does not satisfy all use cases.

In such cases I would call the following function on keyup.

function imposeMinMax(el){
  if(el.value != ""){
    if(parseInt(el.value) < parseInt(el.min)){
      el.value = el.min;
    }
    if(parseInt(el.value) > parseInt(el.max)){
      el.value = el.max;
    }
  }
}

Usage example

<input type=number min=1 max=4 onkeyup=imposeMinMax(this)>

This will reset the value to the max value if the user types in a greater value, and will reset it to the min value if the user types in a lesser value.

like image 7
Vincent Avatar answered Oct 19 '22 07:10

Vincent