Jquery – Fire event on enter key press for a textbox

asp.netevent handlingjquery

I have the following asp.net textbox control.

<asp:TextBox ID="txtAdd" runat="server" />

After the user writes something in this textbox and presses the ENTER key, I want to run some code from codebehind.

What should I do?

Using jQuery I captured ENTER key and fired some hidden button event

$(document).ready(function(){ 
   $(window).keydown(function(e){
      if(e.keyCode == 13) $('#<% addbtn.ClientID %>'.click();
   }); 
});

Is there any better way ?

Best Answer

  1. Wrap the textbox inside asp:Panel tags

  2. Hide a Button that has a click event that does what you want done and give the <asp:panel> a DefaultButton Attribute with the ID of the Hidden Button.

<asp:Panel runat="server" DefaultButton="Button1">
   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>    
   <asp:Button ID="Button1" runat="server" style="display:none" OnClick="Button1_Click" />
</asp:Panel>
Related Topic