Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
Is it possible to make a Close/Dismiss button for HTML native <dialog> (no plugin) with <form>?

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.
   })
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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().

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!