Is possible to assign a click event to a button control in a Web form just
pressing the return key? Something like windows forms where you can assign
this action to a default control. For example, if I press Return, I want to
fire the button_click event even when the button is not in focus. Any
thoughts?
Thanks!
Raul
Hey Raul,
Trapping "client-side" events in the web world is done via Javascript.
<obvious statement>
Because the web is a stateless environment you can't actually catch
events in "real-time" with your C# code becuase they happen way after
your code has fired and the user has essentially de-coupled themselves
from your server (i.e. the page has been rendered and sent to the
requesting browser).
</obvious statement>
You'll have to monitor the keypress event somehow (i.e. sticking an
"onclick" event handler in your body statement, or better yet follow the
code below), then call a javascript function that fires on the client-
side that calls the "Click()" event of the button. Of course making
this all work in both IE, Netscape, FireFox and Opera can be a
challenge. This might get you started:
in modern browsers (i.e. IE4+, Mozilla) this should be enough to
register your interest in tracking the keyboard press event:
<script language=javascript>
if(navigator.appName == "Microsoft Internet Explorer")
{
document.attachEvent("onkeypress",checkkey);
}
else if(navigator.appName == "Netscape")
{
document.addEventListener("keypress",checkkey,false);
}
</script>
notice that either of these cases calls a function called "checkkey"
here tis:
<script language=javascript>
function checkkey(e)
{
// this traps keystroke events, then calls the
//"keystrokeresponse" function which is more specialized
//and non-browser type aware.
if(navigator.appName == "Microsoft Internet Explorer")
{
if(event.keyCode==13)
{
event.returnValue=false;
event.cancelBubble=true;
keystrokeresponse(13);
}
}
else if(navigator.appName == "Netscape")
{
if(e.which==13)
{
e.preventDefault();
keystrokeresponse(13);
}
}
}
</script>
We're getting more specialized now. This is, in C# parlance what you
would call the delagate for the event that you subscribed to above. You
could do whatever you want here, but you'd have to write two versions,
one for IE and one for Mozilla. For me, it's easier to pipe both to a
"generic" function now that I've got the browser business sorted out.
The rest of the statements (event.returnValue=flase, e.preventDefault,
etc.) just stop the event from bubbling up to the browser and causing a
postback.
Finnally, the actual function that does the stuff you want to do when
the user presses the enter key:
<script language=javascript>
function keystrokeresponse(keycode)
{
if(keycode==13)
{
// Do some cool stuff like:
var mybutton= document.getElementById"mybutton");
mybutton.Click();
}
}
</script>
Hope this helps!
-SRC