My loyal BizTalk readers :) may be surprised to know I'm pretty handy with writing code as well. As such I've been working on a ASP.Net site recently and had to deal with this weird situation.
If you have a webpage with two buttons 'Ok' and 'Cancel' say, and you set default button like this:
Page.Form.DefaultButton = btnOk.UniqueID;
Now lets say you're doing the right thing in regards to accessibility and paying attention to how your page behaves without the mouse and you tab to the Cancel button and hit the enter key, what do you expect to happen?
You would expect the Cancel button event to fire right? Well actually it doesn't. Even though the Cancel button has the focus, it is the DefaultButton event that fires and therefore it is the Ok button that executes. The exact wrong thing you would want to happen.
DefaultButton is implemented using a javascript method called "WebForm_FireDefaultButton". To fix the issue I've just described the solution was to add a javascript file to the page (in my case it was the Master page) that overloads that method. In a nutshell this overloaded method checks to see if the the focus is on a button and if it was the enter key which was pressed. If those two things are true, the FireDefaultButton is ignored. This is the script that we used:
// In the case where a defaultbutton is programmatically set button A the user tabs the focus to button B and hits the enter key, button A will fire. This is the workaround.
if (typeof(WebForm_FireDefaultButton) != 'undefined' )
var origFireDefaultButton = WebForm_FireDefaultButton;
WebForm_FireDefaultButton = function(event, target) {
if (event.keyCode == 13) {
var src = event.srcElement || event.target;
// Don't call original function if focus is on a button
if (src &&
(src.tagName.toLowerCase() == "input") &&
(src.type.toLowerCase() == "submit" || src.type.toLowerCase() == "button")) {
return true;
}
}
return origFireDefaultButton(event, target);
}
As you can see, fortunately, the script is very lightweight and won't therefore cause much of a performance drag.