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 callsclick
on the button- button
onclick
returnsfalse
- event handling stops (form is not submitted)
If I remove the onclick="return false;"
, then:
keypress
handler runs and callsclick
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:
- Remove
onclick="return false;"
from the button - Remove
return false
from thekeypress
handler
This will display the alert and then submit the form as you expect it to.
精彩评论