Hitting the Enter key in a textbox can sometimes have undesired effects like the wrong submit button being "clicked". the method described below allows you to specify a default button to submit when the user hits the Enter key in a textbox.
When you press a key on your keyboard, the JS onkeypress event is fired. this calla function to which we pass the ID of the button associated with the textbox. the function gets a reference to the button and simuilates a mouse-click on the button. we perform a browser detection because IE and Netscape have different event models. the function finally returns false so that the keypress event is canceled (otherwise a second form submit will be raised ). this works with newer versions of IE/Netscape.
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')"/>
This causes web control button1 to be clicked when the Enter key is hit inside textbox1.