In a previous post, and one that gets googled alot, I talked about trapping the enter key on an entire form. When I endeavored to use my own code, I wondered why I did it the way I did. I don't actually remember why I used a one second buffer to store the enter key press and cancel the form-post. Basically, that approach is something you can add to a webform and forget about it.
I was about to use it on a page I'm authoring and lo-and-behold, the developer ahead of me has abstrated out the web form class and removed my access to the form itself. I have niether access to the html portion of the <form> tag nor access to the form element (or control) from the code behind. So I modified the fuction to provide the following capability:
- trap the enter key from the onKeyPress event of an element and return false when it was the enter key
- provide the id of an alternate element to click() if the enter key was pressed
note: I debated on whether I should return false when the enter key matched. This allows me to say onKeyPress="return trapEnterKeyPress('someElementId');" and the call to the function is pretty straight forward. The truth is I wanted to return true when the enter key was pressed but then the call is onKeyPress="return !trapEnterKeyPress('someElementId');". That ! is easy to miss and other developers might wonder why it doesn't work. Splitting hairs are we? yes!
here is the function
//enter key trap function - traps the enter key.
//If an element id is provided, it will call click on that element if available.
//returns false if the enter key was trapped as source of event
function trapEnterKeyPress(sElementIdToClick){
//is it the enter key?
var bIsEnterKey = (event.keyCode.toString() == '13');
if(bIsEnterKey){
//is there an alternative element to click instead?
if(sElementIdToClick.length>0){
//make sure it exists and is clickable
var oEl=document.getElementById(sElementIdToClick);
if(oEl) if(oEl.click) oEl.click();
}
}
//return true if all clear (see note in article)
return !bIsEnterKey;
}
here's the control declaration in asp.net
<input type="Text" id="Zip" name="Zip" value="<%#_sZip%>"
onKeyPress="return trapEnterKeyPress('<%#button1.ClientId%>');">
which renders in regular html as:
<input type="Text" id="Zip" name="Zip" value="30306"
onKeyPress="return trapEnterKeyPress('_ctl0_button1');">
if an alternate element id is not specified or is not a clickable element, the enter key is just trapped, forcing some other method of submission