【问题标题】:How do I submit a form with multiple fields as soon as no field is focused anymore?一旦不再关注任何字段,如何提交具有多个字段的表单?
【发布时间】:2020-11-07 00:03:30
【问题描述】:

我有一个包含多个字段的 Elementor 表单。我希望在没有关注任何字段(例如单击某处)时自动提交表单。

我对具有单个字段的表单的解决方案如下所示:

$( '#form-field' ).blur( function() {
    $( '#form' ).submit();
});

如何将其扩展到#form 形式的所有字段?

感谢您的帮助!

编辑:

感谢您的回答。

就 favilian 的回答而言,if 语句会很有趣。因此,如果用户离开一个表单域,则必须检查我们是否不在表单的任何其他域中。仅当不在任何其他字段中时,才提交表单。表单看起来(简化)如下:

<form method="post" id="form">
    <input type="text" name="form_fields[field1]" id="form-field-field1">
    <input type="text" name="form_fields[field2]" id="form-field-field2">
    <input type="text" name="form_fields[field3]" id="form-field-field3">
    <button type="submit">Save</button>
</form>

例如,案例一:

用户点击第一个字段 (#form-field-field1) 并离开表单,应该提交表单,因为字段二 (#form-field-field2) 和三 (#form-field-field3) 没有焦点。

案例二:

用户在第一个字段中再次单击并继续到第二个字段(通过单击或选项卡)。这不应该触发提交,因为表单的另一个字段是焦点/活动的。之后,用户通过单击离开表单。没有其他表单域处于活动状态。现在应该提交表单了。

if 语句如何检查是否没有关注另一个字段?

【问题讨论】:

    标签: javascript html jquery forms onblur


    【解决方案1】:

    你可以用哼哼来聆听每一次聚焦

    document.addEventListener('focusout', function

    你可以用document.activeElement告诉当前的activeElement

    所以可能是这样的

    document.addEventListener('focusout', function (e) {
        const active = document.activeElement;
        if ( /active is not an input of form, depends on your html syntax / ) {
           //Submit the form
        }
    });
    

    【讨论】:

    【解决方案2】:

    好的,在朋友的帮助下,我找到了解决方案。 focusout 和新的 focus 之间似乎有一个微小的时刻,这使得超时是必要的。

    $( '#form :input' ).blur( function() {
        setTimeout( function() {
            if ( [...document.querySelectorAll( ':focus' )].length == 0 ) {
                $( '#form' ).submit();
            }
        }, 200 );
    });
    

    【讨论】:

      猜你喜欢
      • 2016-01-20
      • 2021-05-18
      • 1970-01-01
      • 2018-05-08
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多