Search code examples
javascriptcharacter-encodingasciidom-eventskeypress

Javascript event keypress check for Char Code


Statement: I have a input field.User enters only Numbers in it. Max allowed value is 500. So if user tries to type a value greater than 500 he should not be able to type the value.

For example:

  1. Hundreds place max value would be 5 if user tries to enter 600 or 700.
  2. Tens and Units place Max value would be 0 if user has typed 5 as the first digit(hundreds place)

PS : The handling for user entering only numbers is done already using the following code snippet:

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

Fix for the Problem:

   function isNumberKey(evt){

     var charCode = (evt.which) ? evt.which : event.keyCode;
     if (charCode > 31 && (charCode < 48 || charCode > 57))
       return false;

     if(!(charCode > 31 && (charCode < 48 || charCode > 57)) && charCode != 8){
      if($(evt.currentTarget).value.length == 3){
                   return false;
        }
   if($(evt.currentTarget).value.length == 2){
    if($(evt.currentTarget).value.substring(0,1) > 5){
               return false;
     }else if($(evt.currentTarget).value.substring(0,1) == 5 && $(evt.currentTarget).value.substring(1,2) > 0 ){
    return false;
      }
       }
   }
      return true;
   };

Solution

  • As i understand you can use onchange instead of keypress:

    $('#textbox').change( function(){
       elem = $(this);
       if(parseInt(elem.val()) > 500)
          elem.val('500');
    });