Friday, June 22, 2012

ASP.NET textboxes that take only numerical values as input

Following is a javascript code snippet for your ASP.NET test.aspx page. Please note the script checkNumber is for non-decimal numbers while checkNumber is for decimal numbers.


<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>User Page</title>
    
    <script language="javascript" type="text/javascript">

function checkNumber(textBox, textEvent )
{
    var  code = textEvent.which; // Netscape Method
    
    if (code == null)
    {
        code = textEvent.keyCode;//IE 4 Method
    }
    
    if(code==13)
    {
    
        
        obj.focus();
        
    }
    if(!((code >= 48 && code <= 57) || (code == 8)))
    {
        return false;
    }
    return true;
}
function checkNumberWithDecimal(textBox, textEvent )
{
    var  code = textEvent.which; // Netscape Method
    if (code == null)
    {
        code = textEvent.keyCode;//IE 4 Method
    }
    if(code==13)
    {
    
        //var obj= getFrmObject(textBox);
        obj.focus();
        
    }
    if(!((code >= 48 && code <= 57) || (code == 8)||(code==46)))
    {
        return false;
    }
    return true;
}

</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        <div style="float:left">Registration No</div>
        <div style="float:left"><asp:TextBox ID="txtRegNo" runat="server"></asp:TextBox></div>
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>
And following is your code on

Page_Load

protected void Page_Load(object sender,EventArgs e)
{
      txtRegNo.Attributes.Add("OnKeyPress", "javascript:return                                     checkNumber(this,event);");

}     

No comments: