I came up with an extensible version of this. In a web application I'm now
working on, we have multiple pages that have form fields on them, some of
which we want to click certain buttons on that form when the ENTER key is
pressed. What I did was to come up with a JavaScript that could be kept in a
User Control common to all of the pages. When we want a certain form field
to click a certain button, we add a case to the switch statement in the main
function, and add an "onfocus" and "onblur" JavaScript event handler to the
form field. The script looks like this:
<script language=javascript type=text/javascript>
var hasFocus = null; // Used to indicate which control has the focus at
any given time
function setFocus(obj) //sets the hasFocus variable to the element which
has received the focus (via onfocus event)
{
hasFocus = obj;
}
function loseFocus() // clears the hasFocus variable when the element loses
focus (via onblur event)
{
hasFocus = null;
}
document.onkeypress =
function checkKeyPress(e)
{
if(!e)e = window.event;
var key = (typeof e.which == 'number')?e.which:e.keyCode;
if(key == 13) {handleKP();
return (false);}
}
function handleKP()
{
if (hasFocus == null) return (false);
switch (hasFocus.id)
{
case "AirportSearch_RegularSearch_txtAirportID":
case "AirportSearch_RegularSearch_txtAirportName":
case "AirportSearch_RegularSearch_txtAirportCity":
document.getElementById('AirportSearch_RegularSearch_btnSearchSubmit').click
();
break;
case "AirportSearch_DistanceSearch_txtAirportCity":
case "AirportSearch_DistanceSearch_txtAirportDistance":
document.getElementById('AirportSearch_DistanceSearch_btnSearchSubmit').clic
k();
break;
case "AirportSearch_AdvancedSearch_txtAirportID":
case "AirportSearch_AdvancedSearch_txtAirportName":
case "AirportSearch_AdvancedSearch_txtAirportCity":
document.getElementById('AirportSearch_AdvancedSearch_btnSearchSubmit').clic
k();
break;
case "HeaderLogin1_txtPassword":
document.getElementById('HeaderLogin1_ImageButtonLoginGo').click();
break;
case "HeaderLogin1_txtAirportID":
document.getElementById('HeaderLogin1_ImageButtonAirportGo').click();
break;
case "Login1_txtUserPassword":
document.getElementById('Login1_btnLoginSubmit').click();
break;
}
return (false);
}
</script>
Here is a sample of an element (HtmlControl on the server) that would be
handled by this script:
<input name="HeaderLogin1:txtPassword" type="text"
id="HeaderLogin1_txtPassword" class="txtLoginBox"
onblur="loseFocus()" onfocus="setFocus(this)" style="width:80px;" />
--
HTH,
Kevin Spencer
Microsoft MVP
..Net Developer
http://www.takempis.com
Neither a follower nor a lender be.