PREVENT POST BACK ON ENTER IN AN ASP.NET INPUT FIELD (ASP:TEXTBOX)

Lets say you have the following ASPX code:

<div id="LoginWraper">  
    <asp:TextBox runat="server" ID="TbUsername" ClientIDMode="Static" />
    <asp:TextBox runat="server" ID="TbPassword" TextMode="Password" ClientIDMode="Static" />
    <asp:Button runat="server" ID="BtnLogin" ClientIDMode="Static" Text="Login"/>
</div>  

If you want to prevent ASP.NET from doing a post back on a “enter press” in “TbUsername” or “TbPassword” when the user is calling himself “Magneto” you will probably end up with something like this:

$("#TbUsername, #TbPassword").on("keypress", function (e) {
    var keycode = (e.keyCode ? e.keyCode : e.which);
    if (keycode == '13') {
        var username = $("#TbUsername").val();
        if (username === "magneto") {
            console.log("magneto is not allowed to login");
            return;
        }
        $("#BtnLogin").click();
    }
});

This JavaScript will not prevent ASP.NET from doing a post back. Your code will be ignored because ASP.NET has made his magic way earlier that your code gets the possibility to execute.

One way to take the control back from ASP.NET is to prevent all further actions when a user hits enter followed by an key press in any input field (except textareas). I ended up with this:

$(document).ready(function () {
    $($("form")[0]).on("keypress", function (e) {
        var keycode = (e.keyCode ? e.keyCode : e.which);
        if (keycode == '13') {
            if ($(e.target).prop("type") === "textarea") {
                return;
            }
            e.preventDefault();
            e.stopPropagation();
            return false;
        }
    });
});

The code is very dependent on jQuery. :)

comments powered by Disqus