What is the best way to manage this kind of situation :
$(\'.element\').each(function() {
$sibling = // find a sibling to $this.
$mainElement = $(
Try with this
$('.element').each(function() {
$(this).siblings('.sibling').change(function() {
var mainElement = $(this).siblings('.element');
// Play here
});
});
One way to do it, is to use a closure. This will capture the variable in $mainElement
, so to speak, using its current value.
$('.element').each(function() {
$sibling = // find a sibling to $this.
$mainElement = $(this); // memorize $(this)
$sibling.change(function($mainElement) {
return function() {
// use $mainElement
}
}($mainElement))
});
jsfiddle example (be sure to blur the textfield, after editing, otherwise .change()
won't fire)
I'd say the easiest bet for you is to use an .each on the siblings, and then finding the relative ".element" for the sibling. Depends on your code of course. Otherwise, something like this might work, even though it feels a bit redundant due to the .each:
$('.element').each(function() {
$(this).siblings('.sibling').change(function() {
var mainElement = $(this).siblings('.element');
// Do whatever you want here...
});
});
$('.element .sibling').each(function( ind, el) {
$parent = $( el ).closest( '.element' );
$( el ).change(function() {
$parent.doSomething();
});
});