Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the form submit event fire when I have stopped propagation at the submit button level?

HTML

<form>
    <input type='text'>
    <button type='submit'>Submit</button>
</form>

JavaScript

$('form').on('submit', function(e) {
    alert('submit');
    e.preventDefault();
});

$('button').on('click', function(e) {
    e.stopPropagation();
    alert('clicked');
});

Fiddle


After watching the great video here, I understand that when I click the submit button, the event bubbles up to the form, and the form's submit event is then triggered. Which explains why "clicked" is alerted before "submit" (before I add e.stopPropagation() to the button handler).

But when I add e.stopPropagation() to the button handler, "submit" is still alerted. Why? I thought that stopPropagation prevents the event from bubbling up to the form, and so the form.on('submit') listener shouldn't be "hearing" an event.

like image 508
Adam Zerner Avatar asked Nov 29 '22 10:11

Adam Zerner


1 Answers

When you click a submit button in a form the click event spawns on the button and bubbles up. The submit event spawns on the form (not the button) and bubbles up from there.

If you stop propagation on the click event you're just stopping the bubbling phase of the click event. This has no effect on the submit event.

To stop the submit action you have to add a check to the submit handler.

Keep in mind that adding e.preventDefault() on the click handler in the button is not enough to prevent the submit event from spawning since there are more ways to submit a form than just clicking a button. (pressing enter in an input field for instance).

like image 128
Halcyon Avatar answered Dec 04 '22 23:12

Halcyon