Blog Stats
  • Posts - 14
  • Articles - 0
  • Comments - 14
  • Trackbacks - 0

 

Call OnClick Event of Button when Enter key pressed in TextBox

Problem: Say you have two Grid View controls on one page, each grid view has a TexBox and a 'search' button above it

TextBox1 btnSearch1                                       TextBox2 btnSearch2

Now if you press 'Enter' key  in TextBox1, it will trigger btnSearch1_click event and when you press 'Enter' key in TextBox2, it still triggers btnSearch1_click


Solution:  Add asp.net Panel tag and set DefaultButton property.

<asp:Panel ID="pnlSearch2" runat="server" DefaultButton="btnSearch2">
          TextBox2 btnSearch2
</asp:Panel>
 

Feedback

# re: Call OnClick Event of Button when Enter key pressed in TextBox

Gravatar Hi,

Try using following code -

function KeyDownHandler(e, btn) {
var eventInstance = window.event ? event : e;

if (window.event) // IE
{
if (eventInstance.keyCode == 13) {
eventInstance.returnValue = false;
eventInstance.cancel = true;
var obj = document.getElementById(btn);
obj.click();
return false;
}
}
else if (eventInstance.which) // Netscape/Firefox/Opera
{
if (eventInstance.which == 13) {
eventInstance.returnValue = false;
eventInstance.preventDefault();
eventInstance.cancelBubble = true;
var obj = document.getElementById(btn);
obj.click();
return false;
}
}
}


on text keypress, attach the above function and pass the id of the button as second parameter like -

txtTemplateName.Attributes.Add("onkeypress", "KeyDownHandler(event, '" + btnSearch.ClientID + "')");

--
Thanks,
Sunil 6/30/2009 1:19 AM | Sunil Sutar

# re: Call OnClick Event of Button when Enter key pressed in TextBox

Gravatar this code doesn't work on IE 8. FireFox OK... 8/17/2009 4:32 AM | Serdar Sezgin

# re: Call OnClick Event of Button when Enter key pressed in TextBox

Gravatar this code is work nice

thank u 9/14/2009 5:54 AM | Raju Singh

# re: Call OnClick Event of Button when Enter key pressed in TextBox

Gravatar Thanks great solutions. 9/15/2009 2:49 PM | Masoni

# re: Call OnClick Event of Button when Enter key pressed in TextBox

Gravatar Thanks a lot sir.. 9/29/2009 6:37 AM | farhan

Post a comment





 

 

 

 

Copyright © faizanahmad