Wednesday, May 15, 2013

Allow only numeric values to be entered in a textbox using JavaScript in Asp.net

Hi in this post i will show how to allow only numeric values to be entered into the text-box.

1. On every keypress event in the textbox i will call this below function, this function will just allow you to enter numeric values and rest of the characters other than number will get blocked.


function isNumber(event) {
   
        var KeyBoardCode = (event.which) ? event.which : event.keyCode;
        if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)) {
                return false;
            }
            return true;
}

Example :


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
      <script language="javascript" type="text/javascript" >
    function isNumber(event) {
   
        var KeyBoardCode = (event.which) ? event.which : event.keyCode;
        if (KeyBoardCode > 31 && (KeyBoardCode < 48 || KeyBoardCode > 57)) {
                return false;
            }
            return true;
}
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" onkeypress="return isNumber(event)" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
</html>





No comments:

Post a Comment