24

Given the following HTML:

<form>
  <input type="number" required>
</form>

The following javascript works fine:

(function( jQuery ) {

    jQuery("input").bind("invalid", function(event) {
        console.log(event.type);
    });

})( jQuery );  

But this javascript code does not:

(function( jQuery ) {

    jQuery("form").on("invalid", "input", function(event) {
        console.log(event.type);
    });

})( jQuery );

Anyone got any idea why?

EDIT: Updated fiddle to correct one: http://jsfiddle.net/PEpRM/1

drummondj
  • 1,483
  • 1
  • 10
  • 11
  • 2
    Probably because the HTML input element can be invalid, but the form element can't, and the invalid event doesn't bubble – adeneo Feb 05 '14 at 22:02

1 Answers1

29

The invalid event does not bubble, it says so in the documentation, so delegated event handlers won't work as the event won't bubble up.

This should work

jQuery("form input").on("invalid", function(event) {
    console.log(event.type);
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • @TravisJ - The question was why it doesn't work with the second example, and the answer is you can't delegate an event that does not bubble, or so I thought? What is the issue then? – adeneo Feb 05 '14 at 22:05
  • But I'm giving the "input" selector to the .on method. The point is that if the form contents are dynamically reloaded then they will loose their event handlers using the .bind method. – drummondj Feb 05 '14 at 22:06
  • 1
    @drummondj - Well, you can't. The event does simply not bubble, so you can't delegate the event, you have to apply the event handler after the element has been inserted into the DOM or find some sort of workaround, and I can't really think of any clever way to get that working. – adeneo Feb 05 '14 at 22:08
  • @dru, that's exactly the problem, when you specify selector with on you create a delegate event in a higher level which will fire if and only if the event bubbles. – gdoron Feb 05 '14 at 22:10
  • @drummondj - I believe that would be the best approach, as anything else would probably involve hacks with intervals or mutation observers, as there is no way to make the event bubble (well, there is, but that's even more complicated) – adeneo Feb 05 '14 at 22:12