Recently, a small function has been developed in the project. Press enter to call background events and share the following information with you:
Front-end code:
<SCRIPT type = "text/JavaScript">
// Specifies the button event to be executed when you press ENTER for textbox.
Function enterpressexecutebuttonaction (textboxid, buttonid ){
If (event. keycode = 13 ){
// Get button event
VaR func = Document. getelementbyid (buttonid). Click;
Document. getelementbyid (buttonid). Focus ();
Func (); // call the event
Event. returnvalue = false;
}
}
// Shield the carriage return event for textbox
Function entereventsaction (){
If (event. keycode = 13 ){
Event. keycode = 0;
Event. returnvalue = false;
}
}
</SCRIPT>
<Asp: textbox id = "textbox1" runat = "server" onLoad = "textbox#load"> </ASP: textbox>
<Asp: button id = "button1" runat = "server" onclick = "button#click" text = "button"/>
Background code:
// Button event
Protected void button#click (Object sender, eventargs E)
{
Response. Write ("nihao 123 ");
}
// Load the event
Protected void textbox1_load (Object sender, eventargs E)
{// The textbox extension method is called.
Textbox1.registerpressenteraction (this. button1, buttontype. Button );
}
There is also a textbox extension method class
Public static class textboxextension
{
/// <Summary>
/// Specifies the button event to be executed when you press ENTER for textbox.
/// </Summary>
Public static void registerpressenteraction (this textbox Textbox, webcontrol button, buttontype)
{
Switch (buttontype)
{
Case buttontype. Button:
Textbox. Attributes. Add ("onkeypress", String. Format ("enterpressexecutebuttonaction (this. ID, '{0}');", button. clientid ));
Break;
Case buttontype. Image:
Break;
Case buttontype. Link:
Textbox. Attributes. Add ("onkeypress", String. Format ("enterpressexecutelinkbuttonaction (this. ID, '{0}');", button. clientid ));
Break;
Default:
Break;
}
Textbox. Attributes. Add ("onfocus", "javascript: This. Select ();");
}
Public static void registerpressenteraction (this textbox Textbox, string button, string buttontype)
{
Switch (buttontype)
{
Case "button ":
Textbox. Attributes. Add ("onkeypress", String. Format ("enterpressexecutebuttonaction (this. ID, '{0}');", button ));
Break;
Case "image ":
Break;
Case "Link ":
Textbox. Attributes. Add ("onkeypress", String. Format ("enterpressexecutelinkbuttonaction (this. ID, '{0}');", button ));
Break;
Default:
Break;
}
Textbox. Attributes. Add ("onfocus", "javascript: This. Select ();");
}
/// <Summary>
/// Specifies the button event to be executed when you press ENTER for textbox.
/// </Summary>
Public static void registerpressenteraction (this textbox)
{
Textbox. Attributes. Add ("onkeypress", "entereventsaction ();");
Textbox. Attributes. Add ("onfocus", "javascript: This. Select ();");
}
}
Hope to help you!