Search code examples
javascriptconfirm

On 'Cancel' confirm() still allows form to submit


function next() {
  return confirm('Are you sure you want to Foo');
}
<form method="GET" action="/foo" onsubmit="next()">
  <input type="hidden" name="delete" value={{$foo} />
  <button class="btn btn-warning" type="submit"> Foo</button>
</form>

I am trying to give the user the option to verify that they want to submit the form. Currently the above code shows the popup confirm box, but the form will submit regardless if 'ok' or 'cancel' is clicked.

My understanding of 'confirm()' was that if 'cancel' was clicked the form submission would be stopped.

How does Confirm() work, and how is it best implemented?


Solution

  • You need to precede the next() with a return in your HTML:

    function next() {
      return confirm('Are you sure you want to Foo');
    }
    <form method="GET" action="/foo" onsubmit="return next()">
      <input type="hidden" name="delete" value={{$foo} />
      <button class="btn btn-warning" type="submit"> Foo</button>
    </form>

    To stop submission, the onsubmit handler needs to return false, which you missed. confirm() returns false when the modal is dismissed.