如何防止在基于web的应用程序中按ENTER键提交表单?


当前回答

这个链接提供了一个在Chrome、FF和IE9以及IE7和ie8的模拟器(IE9的开发者工具(F12)中为我工作过的解决方案。

http://webcheatsheet.com/javascript/disable_enter_key.php

其他回答

如何:

<asp:Button ID="button" UseSubmitBehavior="false"/>

在过去,我总是用类似上面的按键处理程序来完成它,但今天遇到了一个更简单的解决方案。输入键只是触发表单上第一个未禁用的提交按钮,所以实际上所需要的只是拦截试图提交的按钮:

<form>
  <div style="display: none;">
    <input type="submit" name="prevent-enter-submit" onclick="return false;">
  </div>
  <!-- rest of your form markup -->
</form>

就是这样。按键将像往常一样由浏览器/字段等处理。如果进入-提交逻辑被触发,那么浏览器将找到隐藏的提交按钮并触发它。javascript处理程序会阻止提交。

如何:

<script>
function isok(e) {
  var name = e.explicitOriginalTarget.name;
  if (name == "button") {
    return true
  }
  return false;
}
</script>
<form onsubmit="return isok(event);">
<input type="text" name="serial"/>
<input type="submit" name="button" value="Create Thing"/>
</form>

只要给你的按钮命名,它仍然会提交,但文本字段,即显式originaltarget,当你在其中点击返回时,将没有正确的名称。

ENTER键仅仅激活表单的默认提交按钮,这将是第一个

<input type="submit" />

浏览器在表单中查找。

所以不要有提交按钮,而是类似的东西

<input type="button" value="Submit" onclick="submitform()" /> 

编辑:回应评论中的讨论:

如果只有一个文本字段,这就行不通了——但在这种情况下,这可能是理想的行为。

另一个问题是,这依赖于Javascript来提交表单。从可访问性的角度来看,这可能是一个问题。这可以通过用javascript编写<input type='button'/>来解决,然后在<noscript>标签中放入<input type='submit' />。这种方法的缺点是,对于禁用javascript的浏览器,您将在ENTER时提交表单。在这种情况下,由OP决定期望的行为是什么。

我知道没有办法做到这一点而不调用javascript。

I Have come across this myself because I have multiple submit buttons with different 'name' values, so that when submitted they do different things on the same php file. The enter / return button breaks this as those values aren't submitted. So I was thinking, does the enter / return button activate the first submit button in the form? That way you could have a 'vanilla' submit button that is either hidden or has a 'name' value that returns the executing php file back to the page with the form in it. Or else a default (hidden) 'name' value that the keypress activates, and the submit buttons overwrite with their own 'name' values. Just a thought.