Jeeva Jeeva - 16 days ago 6
HTML Question

How to allow numbers from 20 - 50 in a text-field using jQuery

I have text field where only numbers are allowed. But i've one more requirement in this. I want to validate the field when user enters numbers below 20 and above 50. May i know if there is any way to achieve this. Below is simple code for the same.

HTML

<input type="text" name="marksdif" class="form-control" id="marksdif" onkeypress="return isNumber(event)" placeholder="Enter Marks to be Compared" autocomplete="off" >


jQuery

function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}

Answer

Check the number with if condition below 20 and above 50 .

function isNumber(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
    return true;
    }
function check(){
  var input = parseInt($('#marksdif').val());
  
if(input){
  if(input < 20 || input > 50)
     {
  $('#result').html('not Allow range between 20-50')
          }
else{
    $('#result').html('Allow')
         }
  }
else{
  $('#result').html("")
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="marksdif" class="form-control" id="marksdif" onkeypress="return isNumber(event)" oninput="check()" placeholder="Enter Marks to be Compared" autocomplete="off" >
<p id="result"></p>

Comments