user339160
user339160

Reputation:

How to check if enterkey is pressed in a TextBox in asp.net

I have a asp.net Text Box which accepts date in the format MM/DD/YYYY. After entering the date i will hit enter key.if enter key i need to execute server side code.How can we achieve this ?

The problem with Text box is it will fire the Text Changed event only if it looses the focus.

Upvotes: 1

Views: 13934

Answers (4)

James
James

Reputation: 7543

You can use the Panel.DefaultButton property to automatically click a button when the user presses Enter.

For example:

<asp:Panel Id="panel1" runat="server" DefaultButton="btnSubmit">
  <asp:TextBox Id="txtDate" runat="server" />
  <asp:Button Id="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" runat="server" />
</asp:Panel>

If you don't want to show the button, you can set its style="display: none".

Upvotes: 4

HashimR
HashimR

Reputation: 3843

You can call this Javascript function to check whether enter key has been pressed or not.

function checkEnterKeyPress(e)
{
     var key;     
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox     

     if (key == 13){
         alert(key);
     }
}

Upvotes: 0

Saul
Saul

Reputation: 18071

Use the keydown event:

textBox.Attributes.Add("onKeyDown", "KeyDownHandler()");

Have KeyDownHandler() check the pressed key and if correct, submit the surrounding form or invoke an AJAX request. See keyboard codes at Javascript Char Codes.


Alternatively, textbox ID can be injected into jQuery from .aspx and assigned a direct keydown handler:

$('#<%=textBox.clientID%>').keydown(function (e) { /* Do server request; */ });

Upvotes: 1

Ricardo Binns
Ricardo Binns

Reputation: 3246

you set jquery tag

so using jquery u can try something like this

$("#field").keydown(function(e){
     if(e.keyCode === 13)
     {
          // enter event
     }
});

Upvotes: 2

Related Questions