What's the difference between preventDefault() and stopPropagation()

preventDefault prevents the default action that was intended to occur. If you click a button, preventDefault() will stop the button from firing any events, such as a form submit. Use preventDefault() if you want to stop your form from being submitted:

<button id='myform_button'>Submit</button>
<script>
$("#myform_button").click(function(e){
   if ( formIsNotValid() )
   {
      e.preventDefault();
      return false;
   }
   else
   {
      $("#myform").submit();
   }
});
</script>

stopPropagation does the same thing as prefentDefault(), but it also stops the event from bubbling up the event chain. If you have your button inside a div which also has a click event, preventDefault() will only stop the form from submitting. But the click handler for the wrapper will still fire. If you want to shut down everyting, you have to use stopPropagation().

No comments:

Post a Comment