Javascript 提交时关闭客户端验证失败的静态背景模式
在提交表单之前,用户单击按钮打开“确认”模式。在模式中按“应用”时,客户端验证将激发并验证所有字段。到目前为止还不错,但如果验证失败,模式就不会关闭,我无法确定如何关闭 我尝试将eventhandler附加到submit按钮,然后调用myModal.hide(),但什么也没发生。我怀疑其他一些引导js代码存在冲突,但我不知道该怎么做 我已经手动尝试通过从和模式背景中删除类来还原.show(),但最终我阻止了模式再次加载(在纠正验证错误后) 我用的是Bootstrap5,Beta3Javascript 提交时关闭客户端验证失败的静态背景模式,javascript,asp.net-core,bootstrap-modal,client-side-validation,bootstrap-5,Javascript,Asp.net Core,Bootstrap Modal,Client Side Validation,Bootstrap 5,在提交表单之前,用户单击按钮打开“确认”模式。在模式中按“应用”时,客户端验证将激发并验证所有字段。到目前为止还不错,但如果验证失败,模式就不会关闭,我无法确定如何关闭 我尝试将eventhandler附加到submit按钮,然后调用myModal.hide(),但什么也没发生。我怀疑其他一些引导js代码存在冲突,但我不知道该怎么做 我已经手动尝试通过从和模式背景中删除类来还原.show(),但最终我阻止了模式再次加载(在纠正验证错误后) 我用的是Bootstrap5,Beta3 <for
<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>
通过以这种方式使用
new bootstrap.Modal()
,您将使用预先存在的引导模式中的元素创建一个额外的、新的引导模式。将两个不同的模态附加到相同的HTML元素会导致冲突
获取对已创建模态的引用的正确方法是通过,如中所示:
var modal=bootstrap.modal.getInstance(document.getElementById(“confirmStaticModal”);
您能创建一个代码片段或JSFIDLE吗?谢谢。这解决了我的问题。您犯了一个小错误,忘记在引导和getInstance之间添加模式。我已经编辑了你的答案
document.getElementById("confirmApplicationButton").addEventListener("click", (event) => {
var modal = new bootstrap.Modal(document.getElementById("confirmStaticModal"));
modal.hide();
});