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

Text box to accept only number

5.00/5 (8 votes)
27 Dec 2011CPOL 56.4K  
Here is a really simple code for a numeric text box and it will work in all browsers. Only works for web applications. function CheckNumeric(e) { if (window.event) //...

Here is a really simple code for a numeric text box and it will work in all browsers. Only works for web applications.


HTML
<head  runat="server">
    <title></title>
    <script language="javascript" type="text/javascript">
        function CheckNumeric(e) {

            if (window.event) // IE 
            {
                if ((e.keyCode < 48 || e.keyCode > 57) & e.keyCode != 8) {
                    event.returnValue = false;
                    return false;

                }
            }
            else { // Fire Fox
                if ((e.which < 48 || e.which > 57) & e.which != 8) {
                    e.preventDefault();
                    return false;

                }
            }
        }
     
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:textbox id="TextBox1" runat="server" onkeypress="CheckNumeric(event);" 
             xmlns:asp="#unknown"></asp:textbox>
    </form>
</body></head>

License

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