‘return false’ vs ‘e.preventDefault()’ In jQuery


Read {count} times since 2020

I decided to add some improvements to Open and fix some bugs. While I was adding two submit listeners on a form, it didn’t work. I have tried everything but still the problem came up. So, I removed return false; and used e.preventDefault();. It worked !

So, why didn’t the submit listener called on the element ? The problem was return false will do **e.stopPropagation() **and e.preventDefault(). If e.stopPropagation() is ran, then any other submit event handlers of the element won’t call. Here’s the 2 submit calls :

$(".postForm").on("submit", function(){
 // do something .....
 return false;
});
$(".postForm").on("submit", function(){
 // do something other than the first one
});

When you submit the form, the 1st function will run successfully, but the 2nd one won’t run, because return false; stops the calling of second function. If you rewrite the code by using e.preventDefault() like this :

$(".postForm").on("submit", function(e){
 e.preventDefault();
 // do something .....
});
$(".postForm").on("submit", function(){
 // do something other than the first one
});

 

It will call both functions without any problem. Now you know when to use return false; and e.preventDefault();. A short summary :

return false; - calls e.preventDefault(); and e.stopPropagation();
e.preventDefault(); - e.preventDefault(); (Prevents the default action)

 

External Resources

You can see the post where jQuery creator John Resig tells about what return false does.

jQuery Event Object