Javascript To Allow Only Numbers In TextBox Using onkeypress

Hi Friends, Sorry for not updating blog regularly. I have been busy in projects So not getting time to update my blogs regularly. Anyway today I am writing this post to provide code for allowing only numbers in textbox by using onkeypress event for textbox. You can use this validation in a phone field of a form to prevent entering characters and special characters or in any other text field in which you required only numbers.

We will use onkeypress event for text box. onkeypress event is used trigger a function when any one press key on keyboard. So practically what it does, When anyone press any key on keyboard, it call a function which we mention and then in that function it check weather it is number or not. So this is how onkeypress works!

But our aim for this article is to prevent taking characters and special characters into text box and to do this we will write one simple 6 to 7 lines function and then call it via onkeypress. Below is function to allow only numbers :

<script type="text/javascript">// <![CDATA[
function check_number_or_not(evt)
// ]]></script>
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;

Above code will be put between tags and then below is example how you can use this function for any text box.

      <input id="txt_Char" onkeypress="return check_number_or_not(event)" type="text" name="txt_Char" />

I have tried this code and it is 100% working, So you can use it without any hesitation. I always like to help people So let me know if you have any issue with this code. Apart for helping people I am PHP Freelancer, WordPress Developer, WordPress Freelancer India and having 6 years of experience and I am available to hire. Contact me