I’m trying to trigger a button’s click event when a user pushes Enter from a textbox. Here’s my code:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#<%= txtSearch.ClientID %>").keypress(function (e) {
if (e.keyCode == 13) {
alert("Hello");
$("#<%= lbSearch.ClientID %>").click();
}
});
});
</script>
<asp:TextBox ID="txtSearch" runat="server" />
<asp:LinkButton ID="lbSearch" runat="server" onclick="lbSearch_Click" />
All my click event does it redirect to a different page.
When I click on the button, it works. When I push Enter from the textbox in IE, Firefox, or Chrome, it works.
But when I push Enter in Safari, the page just performs a postback, even though the jQuery function gets hit (the alert shows).
Any reason for this?
You need to run
e.preventDefault();after determining that it is the enter key. Otherwise, the form posts before the javascript gets a chance to finish running.