Loading ...

How to disable enter key with jQuery | CodeAsp.Net

How to disable enter key with jQuery

 /5
0 (0votes)

In this blog I will show how to disable enter key with jQuery. In many scenarios we need to disable the enter key on a input textbox so that the click event of default button set should not get fired. Below is the source code for it :

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
    <form runat="server">
    <div>
        <asp:Panel ID="Panel1" runat="server" DefaultButton="btnSubmit">
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
            <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox><br />
            <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox><br />
            <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
        </asp:Panel>
    </div>
    </form>
</body>
<script type="text/javascript">

    $(function () {
        $('input').keypress(function (e) {
            var code = null;
            code = (e.keyCode ? e.keyCode : e.which);
            return (code == 13) ? false : true;
        });
    });

</script>
</html>

Above I have used four textboxes and one submit button . I have placed all these controls in a panel  and I have set the default button for this panel. In normal behavior on pressing the enter key inside these textboxes would fire the submit click event but I have disabled the enter key with this code:

            var code = null;
            code = (e.keyCode ? e.keyCode : e.which);
            return (code == 13) ? false : true;

 

i.e. if event code is 13 (which is the key code of eneter key) we will return false which means we have disabled the enter key event.

 

Do let me know your feedback, comments.

Comments (no comments yet)

Top Posts