Reputation: 2133
I need to bind the change of all the textboxes(having class .box
) under Box2 column who have the blue button(having class .blue
which is dynamic in some cases) in their row.
Below is the screenshot of the HTML I have which is just a HTML table which has 3 columns(Box1,Box2 & for the button):
Class .blue
could be present on some buttons on the page load & also could be removed/added to the buttons as result of another Ajax operation.
jQuery .on()
has
.on( events [, selector ] [, data ], handler )
is it possible to use .filter()
in the selector part where I can use a function like
jQuery('.box').filter(function(){
return jQuery(this).closest('tr').find('.blue').length
});
to filter out the needed textboxes & then bind there change event?
Considering the #parent
is the parent div of the HTML I was trying
jQuery('#parent').on('change','.box',..);
but this will listen to the change of all the box2 elements whereas I want it to listen to the specific ones only.
Ideas please?
Thanks.
Upvotes: 1
Views: 1366
Reputation: 36599
In event delegation, we are binding events on the parent element and listening events on it based on the target(
selector
). The only thing we are certain about is thespecific-selector
of the target-element. Well, in the cases linkspecific-child
orspecific-sibling
of the dynamically appended element, doing things in the handler(callback) is the only way!
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
Note: Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents. [Reference]
Upvotes: 1
Reputation: 15786
Include a separate check for the button. Without any code it's not possible to give you the correct code
jQuery('#parent').on('change','.box',..);
if ($(this).next().hasClass('blue')) {
// Do other stuff
}
Upvotes: 1
Reputation: 32354
use a if to test if the button(.box) has a blue class
$('.parent').on('change','.box2 input',function(){
if($(this).closest('tr').find('.box').is('.blue')) {
//do code here
}
});
Upvotes: 1