Adrien Gorrell
Adrien Gorrell

Reputation: 1319

Change() inside each() jQuery

What is the best way to manage this kind of situation :

$('.element').each(function() {

    $sibling = // find a sibling to $this.
    $mainElement = $(this); // memorize $(this)
    $sibling.change(function() {
       // when sibling changes
       // do something using $mainElement
       // problem is, $mainElement is not the element you think
       // $mainElement is the last .element found....
    })
});

One solution would be a table... But then there is no advantage for the change() to be nested in the each()...

My html example :

<div id="first">
  <span class="element"></span>
  <input name="first" type="text" />
</div>
<div id="second">
  <span class="element"></span>
  <input name="second" type="text" />
</div>

In this exemple, $sibling = $(this).next('input'); for instance.

Upvotes: 5

Views: 32682

Answers (4)

Decent Dabbler
Decent Dabbler

Reputation: 22783

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)

Upvotes: 9

Roko C. Buljan
Roko C. Buljan

Reputation: 206078

$('.element .sibling').each(function( ind, el) {

    $parent = $( el ).closest( '.element' );
    $( el ).change(function() {
         $parent.doSomething();
    });

});

Upvotes: 1

GautamD31
GautamD31

Reputation: 28763

Try with this

$('.element').each(function() {
    $(this).siblings('.sibling').change(function() {
       var mainElement = $(this).siblings('.element');
        // Play here
    });
});

Upvotes: 1

Somersault
Somersault

Reputation: 11

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...
    });
});

Upvotes: 0

Related Questions