Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

127
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda