Classes struggle, some classes triumph, others are eliminated. --Mao Zedong
Missouri Sycamores - 11/2011. Copyright © Steve Lautenschlager

How Can I Use Javascript to Allow Only Numbers to Be Entered in a TextBox?

By steve on January 11, 2007.
Updated on January 12, 2013.
Viewed 381,193 times (144 times today).
DeveloperTips and TutorialsJavascript

Summary

Here I show how to use Javascript to allow only numbers to be entered in a textbox. This is useful for phone numbers, IDs, ZipCodes, and, well, that's about it.

This solution works in both IE and Netscape/Mozilla.

Try it here! Just type in the text box below. Note that digits are allowed and alphabetic characters are not allowed. Observe, too, that arrow keys and backspace are allowed so that you can still edit what you type.

To filter out different keystrokes besides numbers check out my javascript keycode page.

Try It!

Example: Allow only numbers/digits in TextBox

<HTML>
   <HEAD>
   <SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

         return true;
      }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
   </BODY>
</HTML>
Back to Top
comments powered by Disqus
Welcome to my blog about software development and the Microsoft stack.

I've been a full time .NET developer for ten years, but I didn't start my professional life as a programmer ... more

Subscribe to my email newsletter for news, updates and more!

Sign Up!

Share/Print this page: