Skip to content Skip to sidebar Skip to footer

How To Limit The Max And Min Value Of Number In Html Text Field

I have a text field which should allow the user to enter numbers,the maximum length should be 2 and the maximum value should be 31 and minimum value should 1 I am able to first 2 c

Solution 1:

document.querySelector("*[name=ccdate]").addEventListener("input", function () {
    var num = +this.value, max = 31, min = 1;          //converts value to a Numberif(!this.value.length) returnfalse;               //allows empty fieldthis.value = isNaN(num) ? min : num > max ? max : num < min  ? min : num;
});

http://jsfiddle.net/cha9t3g5/2

Solution 2:

Try this(Purely Jquery approach):

HTML :

<input type="text"  name = "ccdate"class="form-control" maxlength="2">
<divid="div1"></div>

JQUERY :

$('[name="ccdate"]').keyup(function(){
  if(parseInt($(this).val()) > 31){
    $('#div1').html('value cannot be greater then 31');
    $(this).val('');
  }
  elseif(parseInt($(this).val()) < 1)
  {
    $('#div1').html('value cannot be lower then 1');
    $(this).val('');
  }
  else
  { $('#div1').html(''); }
});

Working Demo


EDIT :-(as per questioner comment to check user entered string or number):

$('[name="ccdate"]').keyup(function(){
  if(isNaN($(this).val()))
   {
    $('#div1').html('entered string');
    $(this).val('');
   }
  elseif(parseInt($(this).val()) > 31){
    $('#div1').html('value cannot be greater then 31');
    $(this).val('');
  }
  elseif(parseInt($(this).val()) < 1)
  {
    $('#div1').html('value cannot be lower then 0');
    $(this).val('');
  }
  else
  { $('#div1').html(''); }
});

Working Demo


EDIT :- (Pure Javascript approach)(Just provide a unique id to your textbox say 't1')

document.getElementById('t1').addEventListener('keyup', function(){
this.value = (parseInt(this.value) < 1 || parseInt(this.value) > 31 || isNaN(this.value)) ? "" : (this.value)
});

Working Demo

Solution 3:

Use min and max attributes and if you want user to enter numbers then give input type as number instead of giving it as text...

<inputtype="number" name ="name_u_want_to_give"min="1"max="31" maxlength="2" />

Solution 4:

Please correct the following code as per your requirements.

`<scripttype="text/javascript">functionminmax(value, min, max) 
{
    if(parseInt(value) < 0 || isNaN(value)) 
        return0; 
    elseif(parseInt(value) > 100) 
        return100; 
    elsereturn value;
}
</script><inputtype="text"name="textWeight"id="txtWeight"maxlength="5"onkeyup="this.value =minmax(this.value, 0, 100)"/>`

Post a Comment for "How To Limit The Max And Min Value Of Number In Html Text Field"