How to get similar functionality with enter key and mouse clicking a button

I have inherited an ASP.NET 1.1 web application.

On the page there are various buttons, textboxes and other controls. There is also a password textbox and password button. If the user types in the password and presses the enter key (while the focus is in the textbox) then I need it to kick off the code behind’s btnPassword click event handler.

Here is the JavaScript that I have that is supposed to give me this functionality:

<script language="javascript" type="text/javascript">
     function kPress(e, buttonId) {
          var evt = e ? e : window.event;
          var bt = document.getElementById(buttonId);

          if (bt) {
               if (evt.keyCode == 13) {
                    bt.click();
                    return false;
               }
          }
     }
</script>

When clicking on the password button with the mouse an error message is displayed if the password is invalid. This is correct. If I click enter while the focus is on the password textbox then I get a different result. It does go on the btnPassword click event handler, but then it looks like as if the page resets itself and looks like when the page first loaded up.

Is the JavaScript code above the the same as when physically clicking the button with the mouse? If not how would I need to change it so that I get similar functionality?

Here is my markup:

<INPUT id="txtPassword" runat="server" type="password" NAME="txtPassword" onkeypress="kPress(event, 'btnPassword');">
<asp:button id="btnPassword" runat="server" Text="OK" CssClass="buttonDefault"></asp:button>

18 thoughts on “How to get similar functionality with enter key and mouse clicking a button”

  1. <script language="javascript" type="text/javascript">
     function kPress(e, buttonId) {
          var evt = e ? e : window.event;
          var bt = document.getElementById(buttonId);
    
          if (bt) {
               if (evt.keyCode == 13) {
                   evt.cancelBubble = true; 
                   evt.returnValue = false;
                   //if browser not ie evt.preventDefault();
                    bt.click();
                    return false;
               }
          }
     }
    

    Reply
  2. I just needed to add a return to the onkeypress event:

    <INPUT id="txtPassword" runat="server" type="password" NAME="txtPassword" onkeypress="return kPress(event, 'btnPassword');">
    
    Reply

Leave a Comment