簡體   English   中英

提交時在客戶端驗證失敗時關閉 static 背景模式

[英]Close static backdrop modal on failed client-side validation when submitting

在提交表單之前,用戶單擊一個按鈕以打開“確認”模式。 在模態客戶端驗證中按“應用”時會觸發並驗證所有字段。 到目前為止一切順利,但如果驗證失敗,模式不會關閉,我無法弄清楚如何。

我試圖將事件處理程序附加到提交按鈕,然后調用 myModal.hide(),但沒有任何反應。 我懷疑其他一些引導 js 代碼存在沖突,但我不知道該怎么辦?

我已經手動嘗試通過從模態背景中刪除類來revert.show(),但最終我阻止模態再次加載(在更正驗證錯誤之后)

我正在使用 Bootstrap 5,beta 3。

<form method="post">
    <div class="mb-1">
        <div class="form-floating pb-0">
            <input type="text" class="form-control" asp-for="Input.Title" placeholder="Title">
            <label asp-for="Input.Title">Event title</label>
        </div>
        <span asp-validation-for="Input.Title" class="text-danger"></span>
    </div>
    <button type="button" class="btn" data-bs-toggle="modal" data-bs-target="#confirmStaticModal">

    <div class="modal fade" id="confirmStaticModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="confirmStaticModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="confirmStaticModalLabel">Apply</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Cancel</button>
                    <input type="submit" class="btn btn-success" value="Apply" id="confirmApplicationButton" />
                </div>
            </div>
        </div>
    </div>
</form>

添加事件處理程序的 JS 代碼

document.getElementById("confirmApplicationButton").addEventListener("click", (event) => {
    var modal = new bootstrap.Modal(document.getElementById("confirmStaticModal"));
    modal.hide();       
});

通過以這種方式使用new bootstrap.Modal() ,您正在使用來自預先存在的 Bootstrap 模態的元素創建一個額外的、新的 Bootstrap 模態。 將兩個不同的模態附加到相同的 HTML 元素會導致沖突。

獲取對已創建模式的引用的正確方法是通過.getInstance()如下所示:

var modal = bootstrap.Modal.getInstance(document.getElementById("confirmStaticModal"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM