2012-09-07 18 views
1

可能重複:
Prevent Users from submitting form by hitting enter在JavaScript提交形式在瀏覽器和多線程

我寫了一些簡單的代碼(you can also test it here

<form > 
     <input id="id2" type='text' /> 
</form> 
$("#id2").keydown(function(e) { 
    if (e.keyCode == 13) { 
     alert('nope!'); 
     return false; 
    } 
}); 

如果我點擊進入我應該看到一個警告「不!」然後什麼也沒有。但是,在我單擊警告窗口上的「確定」後,儘管函數返回false,表單仍在提交。

這是什麼?在javascript中有什麼奇怪的多線程?錯誤?還是......

回答

2

使用keypress事件,而不是​​事件:

$("#id2").keypress(function(e) { 
    if (e.keyCode == 13) { 
     alert('nope!'); 
     return false; 
    } 
}); 

Updated demo

相關問題