E.preventDefault () prevents the default behavior, but returns false. What for?
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 does return false do NOT prevent default behavior, and e.preventDefault() work as intended?
According to this answer :
return falsemakes three separate objects when you call it:
event.preventDefault();event.stopPropagation();- Stop the callback and return immediately when called.
So, event.prevendDefault() called. Does this only happen in jQuery callback?
Since you are attaching your event through addEventListener , and not through the onsubmit attribute of the HTML form element itself, you need to set the return value through the event that is passed to the event handler using returnValue . This is why you see preventDefault working - because it is an event property. Try the following:
document.getElementById("myForm").addEventListener("submit", function (e) { if (document.getElementById("myCheckbox").checked) { e.returnValue = false; // <- Note } else { e.preventDefault(); } }); The difference is that since return not called, execution will continue to pass this statement, so you need to change your logic accordingly. So I added an else block.