Following this example, I create a simple dialog that contains a 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>
However since the input has required attribute, user cannot click it without filling it. I know I can add a click event to Cancel button and close the dialog but I have many dialogs like this and it's better if there is a general native solution.
I need a solution that closes the dialog; and sets its returnValue to empty ("") if close event is raised by such button.
Current workaround:
document.querySelector("#btn-cancel")
.addEventListener("click", () => {
diag.close(""); // Have to set this since onclose event is raised.
})
I think you should be using dialog.close() in your cancel button event listener.
Doing so will discard all of the dialog and thus get rid of all unfilled inputs.
The form will not get submitted on dialog.close().