Jon's Blog

.NET Development & More

That Pesky Enter Key: JavaScript to the Rescue

OK, this solution was put together Frankenstein style from multiple sources.  Basically I wanted to only allow the user to use the Enter key in specific circumstances.  If they were typing their query in the search box, for example.  This solution uses a combination of JavaScript and the ASP.NET Panel control.  The following JavaScript is placed in the MasterPage:

<script type="text/javascript">
 var allowEnterKey = false;
 window.document.onkeydown = CheckEnter;

 function CheckEnter()
  var keyID = (window.event) ? event.keyCode : e.keyCode;

  if (!allowEnterKey && keyID == 13)
   return false;
   return true;


Then my search box (or whatever) can be wrapped in a Panel control like so:

<asp:Panel ID="pnlSearch" runat="server" DefaultButton="btnSearch">
    <div id="SearchDiv">
        <asp:TextBox ID="txtSearch" runat="server" Columns="60" 
            onfocus="allowEnterKey=true" onblur="allowEnterKey=false" />
        <asp:Button ID="btnSearch" runat="server" Text="Search" 
            onclick="btnSearch_Click" onfocus="allowEnterKey=true" onblur="allowEnterKey=false" />


Notice the DefaultButton property set on the Panel as well as the onfocus and oblur properties of the TextBox.