开发者

Unexpected submit on "submit" button click

If I make submit button active (with Tab button), and then press Enter, keypress handler will fire, and will generate click event on button. But OnClick and Submit handlers will not fire. It'll just silently post the form. Why?

<script src="../js/jquery.js" type="text/javascript"></script>
<script type="application/javascript">

$().ready(function(){
     $("#f1").keypress(function(event) {
          if (event.keyCode==13){
            var currentInputId = $(event)[0].target.id;
            var currentInput = $('#'+currentInputId);
            currentInput.click();
            return false;
         开发者_运维百科 }
      });


  $("#f1").submit(function(){
   alert ("huy")
  })
})
</script>
<form name="f1" id="f1" method="POST">
<input type="text">
<input type="submit" onclick="return false;" id="submit">
</form>


Answer rewritten from scratch

On my machine what happens in your scenario (move input on submit button, then press ENTER) is:

  • keypress handler runs and calls click on the button
  • button onclick returns false
  • event handling stops (form is not submitted)

If I remove the onclick="return false;", then:

  • keypress handler runs and calls click on the button
  • form is submitted without the submit handler being called

A few more tests indicate that the submit handler is not being called *because you return false from the keypress handler.

So, to solve the issue:

  1. Remove onclick="return false;" from the button
  2. Remove return false from the keypress handler

This will display the alert and then submit the form as you expect it to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜