skip to Main Content

i have this form action:

<form action="https://google.com">
    <input type="text" required>
    <input type="submit" onclick="mostra(this, form)">
  </form>
  <script>
    function mostra(that, form) {
      if (form.checkValidity()) {
        if (confirm('Sei sicuro di inviare la richiesta?')) {
          that.disabled = true;
          that.value = 'porca madonna';
          form.submit();
        } else {
          alert("else");
          return false;
        }
      }
    }
  </script>
  

When the pop up of the confirm() method comes out and i click cancel, the flow of the code correctly enter in the else, but the form is sent anyway.

I tried to use <input type="button" onclick="mostra(this,form)"> and it works correctly, so the flow it’s different between ok and cancel, but the popup of the of the HTML required prorperty if the input is empy is never showed. Here, i understand that it’s because the form need to be submitted and not just "clicked".

So i think that the first code is better. How i can solve my problem and have the correct flow?
Thank you

2

Answers


  1. Prevent the submit event instead of returning false on click

    const form = document.querySelector('form')
    
    form.addEventListener('submit', mostra)
    
    function mostra(e) {
      if (form.checkValidity()) {
        if (confirm('Sei sicuro di inviare la richiesta?')) {
          that.disabled = true;
          that.value = 'porca madonna';
          form.submit();
        } else {
          alert("else");
          e.preventDefault()
        }
      }
    }
    <form action="https://google.com">
      <input type="text" required>
      <input type="submit">
    </form>
    Login or Signup to reply.
  2. The button type "Submit" is inside a form and when the form is submitted the page is reloaded. You need cancel the default action of the event with the preventDefault() method.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search