Sunday, 8 September 2013

Javascript - Allow textbox only numeric on enter

Javascript:

        Using Javascript we can enable a textbox to allow only numeric , this is can done by following function. use the onkeydown this event is fires when user enter the value in Textbox.Passes the event as parameter to the function using that get the keyCode from that event. keyCode is case sensitive. Based on the keyCode validate and return the boolean type to onKeydown event.

keyCode : 48-57 is numeric type

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript">
    function numeric(ent) {

        ent = (ent) ? ent : window.event;
        var keycode = (ent.keyCode) ? ent.keyCode : ent.which;
        if(keycode > 31 && (keycode < 48 || keycode > 57))
        {
        return false;
        }
        else
        {
        return true;
        }
    }
</script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox runat="server" ID="txt" onkeydown="return numeric(event);"></asp:TextBox>
    </div>
    </form>
</body>
</html>





No comments:

Post a Comment