e.preventDefault() prevents the default behavior, but return false not. Why?
Asked Answered
M

1

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

Muckraker answered 11/6, 2014 at 6:29 Comment(3)
In jQuery only, yes, but not in vanilla JS.Subterrane
@Subterrane That's my guess, as well. I always believed that return false is handled by browser, not by jQuery.Dactyl
You could have read the accepted answer of the question that you have specified as well.Endplay
S
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.

Show answered 11/6, 2014 at 6:38 Comment(6)
You mean onsubmit attribute instead of onclick, right?Dactyl
@IonicãBizãu yes, thank you! Too early in the morning :)Show
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?Dactyl
I honestly did not know that there was a difference between using on* event handlers and addEventListener.Byblow
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?Subterrane
@RoryMcCrossan Any feedback on these comments?Dactyl

© 2022 - 2024 — McMap. All rights reserved.