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?
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With