Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Text box to accept only number

4.13/5 (21 votes)
23 Apr 2011CPOL 94.3K  
Text box to accept only number
<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>


Just paste the Script Section in the Head section and in on key press call the function.
For C#, just paste the following code:

function allownumbers(e) {
        var key = window.event ? e.keyCode : e.which;
        var keychar = String.fromCharCode(key);
        var reg = new RegExp("[0-9.]")
        if (key == 8) {
            //alert(key);
            keychar = String.fromCharCode(key);
        }

And in PageLoad:
txtNum.Attributes.Add("onkeypress", "javascript:return allownumbers(event);");

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)