I want to give my users the option to use a textbox and press Enter. The challenge is that I have 5 textbox, and 2 options. 3 textbox belong to one button, and 2 textbox to the other. How do I trigger a particular Button according to the textbox the user was in when he press Enter?
I accomplished this on my own where I had a page with two different login forms for the different user types. What I did was separate the two forms into their own ASP Panel controls and on the panel setting the DefaultButton to whichever one I wished. That way when they finished typing in the form and hit the enter key, it would submit on the correct button.
Example:
<asp:Panel id="panel1" DefaultButton="button1">
<asp:textbox id="textbox1"/>
<asp:textbox id="textbox2"/>
<asp:buton id="button1"/>
</asp:panel>
<asp:panel id="panel2" DefaultButton="button2">
<asp:textbox id="textbox3"/>
<asp:textbox id="textbox4"/>
<asp:button id="button2"/>
</asp:panel>
EDIT: Here is another method of how to do it by assigning an OnKeyPress property to your textboxes. THIS IS A SEPARATE SOLUTION THAN THAT WHICH I DESCRIBED AT THE TOP
Example:
function clickButton(e, buttonid){
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt){
if (evt.keyCode == 13){
bt.click();
return false;
}
}
}
//code behind
TextBox1.Attributes.Add("onkeypress",
"return clickButton(event,'" + Button1.ClientID + "')");
The code behind generates the following code:
<input name="TextBox1" type="text" id="TextBox1" onkeypress="return
clickButton(event,'Button1')" />
Using jQuery this is fairly easy to accomplish:
$(function ()
{
$("#id-of-textbox-1, #id-of-textbox2, etc.").keyup(function (e)
{
if (e.keyCode === 13) $("#id-of-submit-button-1").click();
});
// And for the second group
$("#id-of-textbox-3, #id-of-textbox4, etc.").keyup(function (e)
{
if (e.keyCode === 13) $("#id-of-submit-button-2").click();
});
});
If you are using ASP.NET Button controls, be sure to set the property UseSubmitBehavior
on those to false.
In this situation I would group the related textboxes and the button in a Panel. Panel has a DefaultButton property you can use. DefaultButton="IdOfTheDefaultButtonForControlsInThisPanel"
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.panel.defaultbutton.aspx