我有以下javascript在我的页面似乎不工作。

$('form').bind("keypress", function(e) {
  if (e.keyCode == 13) {               
    e.preventDefault();
    return false;
  }
});

我想在进入时禁用提交表单,或者更好的是,调用我的ajax表单提交。任何一种解决方案都是可以接受的,但上面包含的代码不会阻止表单提交。


当前回答

在firefox中,当你按下input并按下enter,它会提交它的上层形式。解决方案是在提交表单中添加以下内容:

<input type="submit" onclick="return false;" style="display:none" />

其他回答

更短:

$('myform').submit(function() {
  return false;
});

3年过去了,没有一个人能完全回答这个问题。

请求者希望取消默认的表单提交并调用自己的Ajax。这是一个简单的要求和简单的解决方案。不需要拦截每个输入中的每个字符。

假设表单有一个提交按钮,无论是<button id="save-form">还是<input id="save-form" type="submit">,执行:

$("#save-form").on("click", function () {
    $.ajax({
        ...
    });
    return false;
});

您可以在纯Javascript中完美地做到这一点,简单且不需要库。以下是我对类似话题的详细回答: 禁用表单输入键

简而言之,代码如下:

<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true);
</script>

This code is to prevent "Enter" key for input type='text' only. (Because the visitor might need to hit enter across the page) If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...

如果keyCode未被捕获,则捕获哪个:

$('#formid').on('keyup keypress', function(e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) { 
    e.preventDefault();
    return false;
  }
});

编辑:错过了它,最好使用键up而不是按键

编辑2:在一些较新版本的Firefox中,表单提交不会被阻止,因此在表单中添加按键事件会更安全。它也不能工作(不再?),只是将事件绑定到表单“name”,但只绑定到表单id。因此,我通过适当地更改代码示例使这一点更加明显。

修改bind()为on()

我听说哪个是不推荐的,所以把最佳评分的答案改成这个。

$('#formid').on('keyup keypress', function(e) {
  if (e.key === 'Enter') { 
    e.preventDefault();
    return false;
  }
});

引用https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which