Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issue with jquery delegate and change event

Tags:

jquery

I'd like to use the delegate function with my file change event but I'm not having any luck. Here is what I'm trying to do:

$("#file").delegate("change", function() {    
    $("#submit_form").trigger('click');
});

My change event isn't getting called...am I missing something or can I not use delegate with a change event?

like image 933
Paul Avatar asked Dec 03 '11 16:12

Paul


1 Answers

.delegate() requires a selector representing the targeted element.

$("#file").delegate('.selector_of_element_to_watch', "change", function() {    
    $("#submit_form").trigger('click');
});

If the #file element is the one that should trigger the change event, then don't use .delegate.

$("#file").bind("change", function() {    
    $("#submit_form").trigger('click');
});

The reason for this is that a delegate handler is placed on an ancestor of the element that should trigger the event. You then provide a selector of that element.

Events on the page bubble. That means that the event will propagate from the element that actually triggered the event, all the way up to the window, attempting to trigger a handler on each element along the way.

When the ancestor to which you bound the delegate handler is reached, it will test the event to see if the element that originally triggered the event matches the selector. If so, it will run your code. If not, nothing will happen.


The way to do event delegation in jQuery 1.7 or later is to use the on method.

This method lets you bind directly to the element or to provide a selector for delegation.

So for delegation:

$("#file").on( "change", '.selector_of_element_to_watch', function() {
      // Run if a descendant of '#file' that matches the selector
      //    '.selector_of_element_to_watch' triggered the event
    $("#submit_form").trigger('click');
});

Or for direct binding:

$("#file").on( "change", function() {
      // Run if '#file' itself, or ANY of its descendants triggered the event
    $("#submit_form").trigger('click');
});

(Not knowing what type of element #file is, it's possible that it doesn't/cant' have descendants. If that's the case, then obviously event delegation is not the proper solution.)

This is much improved over their old API of bind/live/delegate, and should have been how it was done from the start.

like image 185
RightSaidFred Avatar answered Nov 15 '22 04:11

RightSaidFred