![](/img/trans.png)
[英]How do I alert the user that multiple fields are left blank in an HTML form after clicking submit?
[英]How do I submit a form with multiple fields as soon as no field is focused anymore?
我有一個包含多個字段的 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 語句如何看起來像檢查是否沒有其他字段被聚焦?
哼,你可以聽每一個焦點
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
}
});
好的,在朋友的幫助下,我找到了解決方案。 在focus
和新focus
之間似乎有focusout
,這使得超時成為必要。
$( '#form :input' ).blur( function() {
setTimeout( function() {
if ( [...document.querySelectorAll( ':focus' )].length == 0 ) {
$( '#form' ).submit();
}
}, 200 );
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.