Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire event on enter key press for a textbox

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 ?

like image 627
ALAN Avatar asked Oct 31 '12 13:10

ALAN


People also ask

How do you trigger a button on a Enter key?

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.

How do you trigger HTML button after hitting Enter button in textbox using JavaScript?

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.

How do you submit a form when Enter key is pressed?

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.


2 Answers

  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> 
like image 55
Jimmy Mattsson Avatar answered Sep 28 '22 21:09

Jimmy Mattsson


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)     {      } 
like image 25
ahaliav fox Avatar answered Sep 28 '22 19:09

ahaliav fox