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

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

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


当前回答

您可以在纯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...

其他回答

当你关注输入元素时,表单通常是按Enter键提交的。

我们可以在表单中的输入元素上禁用Enter键(代码13):

$('form input').on('keypress', function(e) {
    return e.which !== 13;
});

演示:http://jsfiddle.net/bnx96/325/

$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
  if(e.which == 13) {
    e.preventDefault();
    return false;
  }
});

这个解决方案适用于网站上的所有表单(也适用于插入ajax的表单),只防止输入文本中的输入。把它放在文档就绪函数中,然后永远忘记这个问题。

更短:

$('myform').submit(function() {
  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...

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

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