Question

I have successfully used JavaScript confirm() using the onClick event handler.

<input type="submit" onClick="return confirm(....);" />

And I have also successfully used confirm using the onSubmit

<form onSubmit="return confirm(....);">

Now my issue is, there is one specific situation where I want to submit the form by not clicking and just using document.myform.submit() but when ever I do it, it seems to bypass the confirm in the onSubmit event.

How do I use document.whateverform.submit() together with confirm()?

Was it helpful?

Solution

Events are fired when a user performs an action that triggers a state change. Browsers cannot let an onsubmit handler run when the .submit function is called directly via JavaScript. Think about what would happen to code like this:

<form onsubmit="if(someCondition) { this.submit(); }">
...
</form>

If the event fired from the javascript-driven submit, that would trigger an infinite loop because onsubmit calls submit, which calls onsubmit, and so on. I know some people may question whether that is a good pattern, but I have seen it.

You should probably avoid direct calls to form.submit altogether and replace them with a call to the same function, like so:

function confirmFormSubmission() {
  return confirm('Are you sure you want to do this?');
}

function submitForm(f) {
  if (confirmFormSubmission()) {
    f.submit();
  }
}

...

<form onsubmit="return confirmFormSubmission()">
....
</form>

Any place in your JavaScript code that calls form.submit, replace it with a call to submitForm instead to make sure it works consistently.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top