Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 702
Adrien Gorrell Avatar asked Feb 16 '13 12:02

Adrien Gorrell


People also ask

What does .change do in jQuery?

jQuery change() Method The change event occurs when the value of an element has been changed (only works on <input>, <textarea> and <select> elements). The change() method triggers the change event, or attaches a function to run when a change event occurs.

What is the use of jQuery each () function?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How break out of jQuery each?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.

How do you iterate through an element in jQuery?

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0.


2 Answers

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)

like image 52
Decent Dabbler Avatar answered Nov 14 '22 16:11

Decent Dabbler


Try with this

$('.element').each(function() {
    $(this).siblings('.sibling').change(function() {
       var mainElement = $(this).siblings('.element');
        // Play here
    });
});
like image 38
Gautam3164 Avatar answered Nov 14 '22 17:11

Gautam3164