Wednesday, October 23, 2013

Jquery code to allow Numerics(numbers only) in Textbox control in asp.net

Leave a Comment
Jquery can be used to limit the textbox to accept only the numerics(numbers) from the keyboard and not allow any other type of characters. This validation can be used for example phone number or pin code which will be only numeric.

Jquery to accept only Numbers(0-9) for TextBox:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
 $(document).ready(function () {

  $(function () {
                $('#txtname').keydown(function (e) {
                    var pressedkey = e.keyCode;
                    
                      
                    if (e.shiftKey || e.ctrlKey || e.altKey) {
                        e.preventDefault();
                    } else {
                        var key = e.keyCode;
                        if (!((pressedkey == 8) || (pressedkey == 46) || (pressedkey >= 35 && pressedkey <= 40) || (pressedkey >= 48 && pressedkey <= 57) || (pressedkey >= 96 && pressedkey <= 105))) {
                            e.preventDefault();
                        }
                    }

                });


            });

        });


    </script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox runat="server" ID="txtname"></asp:TextBox>


        </div>
    </form>
</body>
</html>

0 comments:

Post a Comment