Reputation: 8038
I have been playing around with a search control and i have noticed that when you try and press enter from within the textbox it submits the form but doesnt click the search button (like i want it to).
My markup is:
<div>
<span>Search</span>
<asp:TextBox ID="txtSearch" runat="server" Width="170"
onkeydown="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {$('#<%=lkbSearch.ClientID %>').click();return false;} else return true; ">
</asp:TextBox>
</div>
<asp:LinkButton ID="lkbSearch" runat="server" CssClass="searchButton">
<asp:Image ID="imgSearch" runat="server" ImageUrl="~/Images/Master/button_go.gif" />
</asp:LinkButton>
i added the onkeydown event to the textboxes, and it runs, but when i try to use JQuery to call the Click() function from the button it does nothing.
How can i make it so when enter is pressed in the textbox it "clicks" the button?
Upvotes: 0
Views: 4167
Reputation: 13122
Since a LinkButton
is added to the page as an <a>
. When you select the button using jQuery you get the element wrapped in jQuery. Because of that calling the click event only triggers the click event, without following the href
.
The following code would simulate clicking the button:
$('#<%= linkbuttonid.ClientID%>')[0].click();
You may replace '#<%= linkbuttonid.ClientID%>'
with any selector that will get the correct element. But it is necessary to include [0]
so that click is invoked on the <a>
itself.
Alternately, you could reroute the page to the href:
window.location = $('yourselector').attr('href');
See this question for more information about invoking a click-event for an anchor tag in javascript.
Upvotes: 2
Reputation: 8038
After playing around with a few different things i finally came up with the solution.
I wrapped the textbox and button in an asp:panel control and set the default button to the ID of my LinkButton only to find that panels cant have LinkButtons as the DefaultButton.
But changing the link button to an ImageButton and using its ID in the DefaultButton filed of the panel works perfectly.
<asp:Panel ID="pnlSearch" runat="server" DefaultButton="imbSearch">
...
</asp:Panel>
Upvotes: 0
Reputation: 2915
This doesn't involve jQuery
Page.RegisterHiddenField( "__EVENTTARGET", lkbSearch.ClientID );
I see you're in a div, if you have a panel there's the DefaultButton attribute.
Failing that if you really want to use jQuery, you can use ClientScript.GetPostBackEventReference
Good luck :-)
Upvotes: 1