2

Nothing I do seems to be able to prevent the form from loading a new page. I have the following test code:

<form id="form" onsubmit="return false">
 <input id='input'>
 <input id='submit' type="button" value="click me">
</form>
<script>
 var form = document.getElementById("form")
 form.addEventListener("submit", (ev) => {
   console.log("submit")
   ev.preventDefault()
   ev.returnValue = false
   return false
 })
 form.dispatchEvent(new Event('submit'))
</script>

The page just loads and reloads over and over again. Is this a bug in firefox? I'm on version 60.7.0esr

B T
  • 57,525
  • 34
  • 189
  • 207

3 Answers3

2

You need to make the event cancelable by adding a cancelable property to the EventInit Object that you need to pass to the Event constructor. It is false by default.

Consider MDN Event Documentation:

cancelable: a Boolean indicating whether the event can be cancelled. The default is false.

var form = document.getElementById("form")
form.addEventListener("submit", (ev) => {
  console.log("submit")
  ev.preventDefault()
  ev.returnValue = false
  return false
})
form.dispatchEvent(new Event('submit', {
  cancelable: true
}))
<form id="form" onsubmit="return false">
  <input id='input'>
  <input id='submit' type="button" value="click me">
</form>
zero298
  • 25,467
  • 10
  • 75
  • 100
1

dispatch event forces to submit the form unless you make it cancelable. You can also add <form onsubmit="return false"> a quick solution would be:

<form id="form" onsubmit="return false">
 <input id='input'>
 <input id='submit' type="button" value="click me">
</form>
<script>
 var form = document.getElementById("form")
 form.addEventListener("submit", (ev) => {
   console.log("submit")
   ev.preventDefault()
   ev.returnValue = false
   return false
 })
 let event = new Event("submit", {
  bubbles: true,
  cancelable: true,
});
form.dispatchEvent(event);
</script>

I hope this helps

Saqib
  • 371
  • 2
  • 13
  • Dispatching an event should not force submit of the form if the handlers prevent the default. Also, onsubmit="return false" does not solve the problem. The page still reloads. – B T Jun 21 '19 at 00:18
  • @SaqibRaja If my comment helped, you should at least acknowledge it. – zero298 Jun 21 '19 at 01:05
  • @zero298 By the time I was checking the code I didn't see your one line comment. But for sure I now acknowledge that you had it right as well. Cheers! – Saqib Jun 21 '19 at 01:11
1

This is a Firefox bug since at least 2017, cf. https://bugzilla.mozilla.org/show_bug.cgi?id=1370630

Use the Event's cancelable property until the Firefox team fixes this issue.

ffff
  • 81
  • 5