I have a page with input textboxes and input buttons on it.  All are
contained in a form.  I don't want the Enter button to submit the
form, so I call preventDefault() on all texboxes.  I also don't want
the input button to submit the form, so I call preventDefault() on the
input button.

But, if I call the button.click() event for when Enter is pressed in a
textbox (to simulate a click on the button) it submits the form.  It
seems as if something is not working like it should.

Now...if I "return false" instead of preventDefault(), it works as I
would expect.  But I would have thought that the purpose of
preventDefault() is to cancel the default action of the event, as in
this case to cancel form submission.

Any help with this is greatly appreciated!  Following is some sample
code that exhibts the behavoir.

Thanks,
Hullah

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>
<html xmlns="http://www.w3.org/1999/xhtml";>
    <head>
        <title>Test</title>
        <script language="javascript" type="text/javascript"
src="jquery-1.2.6.js"></script>
        <script language="javascript" type="text/javascript">
          $(function() {
            $(":text").keypress(function(e) {
              if (e.which == 13) {
                e.preventDefault();
              }
            });
            $("#txt").keypress(function(e) {
              if (e.which == 13) {
                $("#btn").click();
              }
            });
            $("#btn").click(function(e) {
              e.preventDefault();
              alert("Button clicked");
            });
          });
        </script>
    </head>
    <body>
      <form method="post" action="test.html">
        <div>
          <input id="txt" type="text" />
          <input id="btn" type="submit" value="Submit" />
        </div>
      </form>
    </body>
</html>

Reply via email to