Saturday, August 9, 2008

Specifying how the enter key will act on your page

When writing application, we normally will write handlers for buttons events or other events but not for the enter or submit event. This becomes an issue because when your user hits enter when visiting your page, two things could happen:
  • Nothing
  • It will trigger the first button the page encounters (which may not be the button event you want to trigger).
One way is to register the __EVENTTARGET to point to the submit button as shown in the following article. Unfortunately, this approach does not work with web control button.

Another approach is to use javascript to do that.

The java script is as follows:

 function clickButton(e, buttonid){ 
var bt = document.getElementById(buttonid);
if (typeof bt == 'object'){
if (e.keyCode == 13){;
return false;
if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1)){
if (event.keyCode == 13){;
return false;

Then register the textbox you want to link to the javascript as follows in the codebehind:

txtLotID.Attributes.Add("onkeypress", "return clickButton(event,'" + btnLotID.ClientID + "')")

This is useful for a web page for performing stock take where you use a scanner to scan the lots or serial number into the textbox and the scanner automatically performs enter.

No comments: