YUH MING SHYY
YUH MING SHYY

Reputation: 1

Why a JQuery function fires only once on the same page

I have a very simple JQuery that takes the user hit "enter" key as clicking a particular button:

$('#<%= txtSearch.ClientID %>').keyup(function (event) {
            if (event.keyCode == 13) {
                $('#<%= btnSearchByRef.ClientID %>').click();
            }
        });

The button click will trigger a postback and display the search result in the same page.

This works great only in the first time. After the first time, this function is never triggered.

Any idea what's wrong? Thanks.

Upvotes: 0

Views: 73

Answers (2)

Nathan Lippi
Nathan Lippi

Reputation: 5227

Maybe a delegated event handler would work? Try this:

$('body').on("keyup",'#<%= txtSearch.ClientID %>', function(){
        if (event.keyCode == 13) {
            $('#<%= btnSearchByRef.ClientID %>').click();
        }
});

The explanation: When you add an event handler, it will only bind to an element once. If that element is refreshed, the binding is lost.

However, this is where delegated event handlers come in (really) handy. Bind to an element that won't refresh (in this case, 'body').

In the code above, if I'm not mistaken, every time 'body' is clicked, it tests if '#<%= txtSearch.ClientID %>' exists. Then if it does, it should execute your command.

Upvotes: 0

Johan
Johan

Reputation: 35194

Since you're using webforms, why not make use of the DefaultButton property?

<form runat="server">
    <asp:Panel runat="server" DefaultButton="button1">
        <asp:TextBox runat="server" />
        <asp:Button id="button1" Text="Default" runat="server" />
    </asp:Panel>
</form>

This property is used to specify which button gets clicked when the Panel control has focus and the enter key is pressed.

Upvotes: 1

Related Questions