简体   繁体   中英

How can I prevent postback while still allowing javascript to run?

One portion of this Asp.Net page contains this:

<asp:Panel runat="server" DefaultButton="get">
    Enter Employee Name or Click Search to Return All:
    <asp:TextBox runat="server" ID="participant" ></asp:TextBox>
    <asp:Button runat="server" ID="get" UseSubmitBehavior="false" Text="Search" />
</asp:Panel>

Which is powered by this:

$(document).ready(function () {
            $("#get").click(function (e) {
                e.preventDefault();
                document.getElementById('<%= userTable.ClientID %>').style.display = "block";
                getUserNames();
            });
            $("#content_contentPlaceHolder_participant").keypress(function (event) {
                if (event.keyCode == 13) {
                    $("#get").click();
                }
            });
        });

This works everywhere but Chrome. Using the enter key to submit this field in Chrome causes a full page reload.

I tried adding this in the code behind, but it prevents the javascript from firing:

participant.Attributes.Add("onkeydown", "return (event.keyCode!=13);");

How can I fix this, so that the enter key does not cause postback, but still fires the JS?

I resolved the issue by adding an additional preventDefault() .

$(document).ready(function () {
        $("#get").click(function (e) {
            e.preventDefault();
            document.getElementById('<%= userTable.ClientID %>').style.display = "block";
            getUserNames();
        });
        $("#content_contentPlaceHolder_participant").keypress(function (event) {
            if (event.keyCode == 13) {
                event.preventDefault(); // <-- added this line
                $("#get").click();
            }
        });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM