6

I have the following simple form:

<form action="" id="myForm">
    Use <code>return false</code> (if not checked,
    <code>e.preventDefault()</code> will be used):
    <input type="checkbox" id="myCheckbox" checked>

    <br/>

    <input type="submit" value="Submit me">
</form>

Then, the JavaScript side:

document.getElementById("myForm").addEventListener("submit", function (e) {
    if (document.getElementById("myCheckbox").checked) {
        return false;    
    }
    e.preventDefault();
});

Why return false does NOT prevent the default behavior, while e.preventDefault() works as supposed?

According to this answer:

return false is doing 3 separate things when you call it:

  1. event.preventDefault();
  2. event.stopPropagation();
  3. Stops callback execution and returns immediately when called.

So, event.prevendDefault() is called. Does this happen in a jQuery callback only?

JSFIDDLE

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474

1 Answers1

0

Because you are attaching your event through addEventListener, not via the onsubmit attribute of the HTML form element itself, you need to set your return value through the event which is passed to the event handler using returnValue. This is why you see preventDefault working - because it is a property of the event. Try this:

document.getElementById("myForm").addEventListener("submit", function (e) {
    if (document.getElementById("myCheckbox").checked) {
        e.returnValue = false; // <- Note
    }
    else {
        e.preventDefault();
    }
});

Updated fiddle

The difference is that because return is not called, execution will continue passed that statement, so you need to amend your logic accordingly. As such, I added the else block.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • You mean *`onsubmit` attribute* instead of `onclick`, right? – Ionică Bizău Jun 11 '14 at 06:39
  • @IonicãBizãu yes, thank you! Too early in the morning :) – Rory McCrossan Jun 11 '14 at 06:40
  • In Romania is morning too. :-) You could simply do: `return e.returnValue = false;` that looks much better. ;-) Can you please add some docs references? Why returning `false` to `addEventListener` doesn't prevent the default behavior while `onsubmit='return false'` do? – Ionică Bizău Jun 11 '14 at 06:46
  • I honestly did not know that there was a difference between using `on*` event handlers and `addEventListener`. – Felix Kling Jun 11 '14 at 06:46
  • What's this `returnValue` stuff? Afaik `returnValue` belongs to the legacy IE event handling model, and is totally a custom property in modern browsers? Have I missed something lately? – Teemu Jun 11 '14 at 06:48
  • @RoryMcCrossan Any feedback on these comments? – Ionică Bizău Nov 15 '14 at 19:46