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 ?
To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.
We can do it by using “keyup”, “keydown”, or “keypress” event listener on textbox depending on the need. When this event is triggered, we check if the key pressed is ENTER or not.
To submit the form using 'Enter' button, we will use jQuery keypress() method and to check the 'Enter' button is pressed or not, we will use 'Enter' button key code value. Explanation: We use the jQuery event. which to check the keycode on the keypress.
Wrap the textbox inside asp:Panel
tags
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>
ASPX:
<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="return EnterEvent(event)"></asp:TextBox> <asp:Button ID="Button1" runat="server" style="display:none" Text="Button" />
JS:
function EnterEvent(e) { if (e.keyCode == 13) { __doPostBack('<%=Button1.UniqueID%>', ""); } }
CS:
protected void Button1_Click1(object sender, EventArgs e) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With