[Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 167
  • Last Modified:

Web app - need to stop enter key from triggering a button.


     I'm designing a VB.NET webform that has a small javascript that places the focus initially in a textbox.  At the bottom are buttons - Add/Edit/Cancel/Delete.  When I hit the enter key at any point on this form, the Add button is triggered (although a few times it's been edit) which disrupts the form.  I want the user to have to click the buttons, or later I will program so that depending on what text box the focus is in triggers different buttons.  I don't ever want enter key to trigger the Add button.  I need a javascript either in my HTML side or that I can just submit the way I do my focus:

            Dim strScript As String = "<script language=JavaScript> document.all('txtScanStock').focus(); </script>"
            Page.RegisterStartupScript("MyScript", strScript)

that will keep the enter key from submitting random buttons, or any at all.  Can someone help me?  Thanks!

1 Solution
Will something like this help?  The only part you need is the <script> in the head, but I put together a form as a sample of capturing the Enter key and ignoring it.  There's an alert in there also just to illustrate that it's working, but you can just comment it out once you're satisfied it works.  I put a comment right above it, so you'll know which line to comment out. Hope that helps.

<script type="text/javascript">
document.onkeypress = ignoreEnter;

function ignoreEnter(e)
  var theKey = window.event? event.keyCode: e.which;
  if (theKey == 13)
    if (window.event)
      event.cancelBubble = true;
    // comment out the line after this to get rid of the alert
    alert("captured enter, but ignoring it");
    return false;

<form onsubmit="alert('you submitted form'); return false;">
    <label for="text1">Text1:</label>
    <input type="text" id="text1" />
  <input type="submit" value="Submit the Form" />
gleznovAuthor Commented:
That's absolutely perfect!!!


Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now