我在一个网站上有一个调查,用户按下回车键(我不知道为什么),不小心没有点击提交按钮就提交了调查(表单),这似乎有些问题。有办法防止这种情况吗?

我在调查中使用HTML, PHP 5.2.9和jQuery。


当前回答

第4.10.22.2节隐式提交的W3C HTML5规范说:

A form element's default button is the first submit button in tree order whose form owner is that form element. If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button. Note: Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)

因此,一种符合标准的禁用表单隐式提交的方法是将禁用的提交按钮作为表单中的第一个提交按钮:

<form action="...">
  <!-- Prevent implicit submission of the form -->
  <button type="submit" disabled style="display: none" aria-hidden="true"></button>

  <!-- ... -->

  <button type="submit">Submit</button>
</form>

这种方法的一个很好的特性是它不需要JavaScript;无论是否启用JavaScript,都需要一个符合标准的web浏览器来防止隐式表单提交。

其他回答

您可以创建一个JavaScript方法来检查是否按下了Enter键,如果按下了,就停止提交。

<script type="text/javascript">
  function noenter() {
  return !(window.event && window.event.keyCode == 13); }
</script>

只需在submit方法上调用它。

Use:

// Validate your form using the jQuery onsubmit function... It'll really work...

$(document).ready(function(){
   $(#form).submit(e){
       e.preventDefault();
       if(validation())
          document.form1.submit();
   });
});

function validation()
{
   // Your form checking goes here.
}

<form id='form1' method='POST' action=''>
    // Your form data
</form>

这里已经有很多好的答案,我只是想从用户体验的角度贡献一些东西。键盘控件在表单中非常重要。

问题是如何在按回车键时禁用提交。而不是如何在整个应用程序中忽略Enter。因此,考虑将处理程序附加到表单元素,而不是窗口。

禁用Enter表单提交仍然允许以下:

当提交按钮被聚焦时,通过输入提交表单。 填充所有字段时提交表单。 通过Enter与非提交按钮交互。

这只是一个样板,但它符合所有三个条件。

$(“形式”)。On ('keypress',函数(e) { //注册按键。 $attr = $(e.target).attr('type'); $node = e.target.nodeName.toLowerCase(); if ($ attr = = =“按钮”| | $ attr = = = '提交' | | $ node = = =“文本区域”){ 返回true; } //如果没有填充所有字段,则忽略按键。 if (e.which === 13 && ! fieldsarepopulate (this)) { 返回错误; } });

不要在输入或按钮中使用type="submit"。 使用type="button"并使用js [Jquery/angular/etc]向服务器提交表单。

进入你的css,把它添加进去,然后会自动阻止公式的提交,只要你有提交输入,如果你不再需要它,你可以删除它,或者输入activate和deactivate

 input:disabled {
        background: gainsboro;
      }
      input[value]:disabled {
        color: whitesmoke;
      }