Last updated on January 10th, 2023 at 11:15 am

There are fields in a form where we need only numbers to be entered by our users, for example fields like pincode, phone numbers, mobile numbers etc., Here is a small function to accomplish this task.

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


Here is the input field in HTML

<input type="text" onkeypress="return isNumberKey(event);">


Explanation: the function isNumberKey() will check whether the entered key code is greater than 31 and between 48 and 57.
48 is assigned to numeric 0[Zero] and 57 to numeric 9[Nine].Otherwise the keys wont be entered inside the input field. There are 128 ASCII characters and their equivalent number.

Leave a Reply

Your email address will not be published. Required fields are marked *