按照这个示例,我创建了一个简单的
dialog
,其中包含一个form
:
const diag = document.querySelector("#diag")
diag.addEventListener("close", () => {
if (!diag.returnValue) { return; }
document.querySelector(".result").textContent = document.querySelector("#txt-name").value;
});
document.querySelector("#btn-show").addEventListener("click", () => {
diag.showModal();
});
<dialog id="diag">
<form method="dialog">
<input id="txt-name" required />
<button value="submit">Submit</button>
<button value="">Cancel</button>
</form>
</dialog>
<button id="btn-show">Show Dialog</button>
<p>Result: <span class="result"></span></p>
但是由于
input
具有 required
属性,用户无法在不填写的情况下单击它。我知道我可以向取消按钮添加 click
事件并关闭对话框,但我有很多这样的对话框,如果有通用的本机解决方案就更好了。
我需要一个关闭对话框的解决方案;并将其
returnValue
设置为空 ("") if close
事件由此类按钮引发。
当前解决方法:
document.querySelector("#btn-cancel")
.addEventListener("click", () => {
diag.close(""); // Have to set this since onclose event is raised.
})
我认为你应该在
dialog.close()
事件监听器中使用 cancel button
。
这样做将丢弃所有对话框,从而消除所有未填充的inputs
。
该表格将不会于dialog.close()
提交。
制作关闭按钮的更合适方法是在按钮/输入元素上使用
formnovalidate
属性。
const diag = document.querySelector("#diag")
diag.addEventListener("close", () => {
if (!diag.returnValue) { return; }
document.querySelector(".result").textContent = document.querySelector("#txt-name").value;
});
document.querySelector("#btn-show").addEventListener("click", () => {
diag.showModal();
});
<dialog id="diag">
<form method="dialog">
<input id="txt-name" required />
<button value="submit">Submit</button>
<button value="" fromnovalidate>Cancel</button>
</form>
</dialog>
<button id="btn-show">Show Dialog</button>
<p>Result: <span class="result"></span></p>