【问题标题】:Form without submit button on EnterEnter 上没有提交按钮的表单
【发布时间】:2018-01-19 14:50:25
【问题描述】:

对于没有提交按钮、有 1 个文本输入的表单,请在 Enter 时提交。

对于没有提交按钮的表单,有超过 1 个文本输入,不要在 Enter 上提交。

两者都不应该在 Enter 时提交吗?

<!-- This one do submit on Enter --> 
<form action="/">
  <input type="text" name="firstname" value="Mickey">
</form>

<!-- This one do not submit on Enter --> 
<form action="/">
  <input type="text" name="firstname" value="Mickey">
  <input type="text" name="lastname" value="Jerry">
</form>

【问题讨论】:

标签: html forms form-submit submit-button


【解决方案1】:

如果表单没有提交按钮,则隐式提交 如果表单有多个字段 阻止隐式提交,并且必须从 否则形成元素本身。

https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#implicit-submission

您可以在此处查看表单如何在没有提交按钮的情况下工作: https://www.tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/#no-submit-buttons

【讨论】:

    【解决方案2】:

    一般来说,将 Enter 键作为提交表单的一种方式是不可行的。放好之后,您可以使用 JavaScript 的 jQuery 库来实现这种功能(它会更容易使用)。

    这是您的 HTML 的修改版本。我添加了一个数据属性来识别那些不会在 Enter 键上提交的表单:

    <!-- This one WILL NOT submit, when the Enter key is pressed -->
    <form action="/" data-disable-enter="1">
        <input type="text" name="firstname" value="Mickey">
    </form>
    
    <!-- This one WILL submit, when the Enter key is pressed
         If you want to suppress the Enter key submission, add the data attribute data-disable-enter="1" -->
    <form action="/">
        <input type="text" name="firstname" value="Mickey">
        <input type="text" name="lastname" value="Jerry">
    </form>
    

    这里是 JavaScript 代码,使用 jQuery 库来抑制 Enter 键表单提交。附加了一个事件侦听器以侦听具有数据属性data-disable-enter="1" 的所有表单中每个表单元素(输入、选择和文本区域)上的keydown 事件。如果按下的按键代码是 13 (which means "Enter"),那么我们将阻止与按键相关联的默认操作,在我们的例子中是表单提交。

    jQuery("form[data-disable-enter='1']").find("input, select, textarea").on("keydown", function(e){
        // 13 is the key code for the Enter key
        if(e.keyCode === 13){
            e.preventDefault();
        }
    });
    

    【讨论】:

    • AFAIK OP 询问为什么在没有submit 按钮/输入的情况下提交表单,他并没有尝试禁用提交本身
    • 我应该删除我的答案吗?
    • 这完全取决于你!如果它没有得到任何反对,你可以把它留在那里,以防将来有人需要它
    猜你喜欢
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多