gonzalomelov
gonzalomelov

Reputation: 981

JQuery click event inside for

I really don´t know what is happening to me..

The code is like:

for (var j=0; j<tours.length; j++){
    var name = tours[j].name;

    var $tourLI = $('<li id="'+name+'"></li>');
    var $tourButton = $('<div class="button-inside"><span>'+name+'</span><span></span></div>');

    $tourButton.click(function() {
        alert(name);
    }
}

I´m trying to bind the click event for each button which displays the tours name, but is always displaying the last tour name whichever the button I'm clicking.

What am I doing wrong?

Thanks!

Upvotes: 0

Views: 834

Answers (4)

nbrooks
nbrooks

Reputation: 18233

You need to wrap the click handler in a closure to 'close-over' the value of the variable name before the for-loop moves on.

This is because the handler isn't actually executed until you click on it, so otherwise it will simply use the current value of name at that time (whatever the last value in the loop was).

for (var j=0; j<tours.length; j++){
    var name = tours[j].name;

    var $tourLI = $('<li id="'+name+'"></li>');
    var $tourButton = $('<div class="button-inside"><span>'+name+'</span><span></span></div>');

    (function(n) {
        $tourButton.click(function() {
            alert(n);
        });
    })(name)
}

Upvotes: 1

bipen
bipen

Reputation: 36531

no need to call click event inside loop..append the dynamically created button and call it outside the loop and use on delegate event

try this

 $(document).on('click','div.button-inside',function() {
    alert($(this).text());
}

you can go through the link if you want to read more about on delegate events...

Upvotes: 0

MG_Bautista
MG_Bautista

Reputation: 2653

Try this...

$('.div.button-inside ').on('click',function() {
    alert($(this).text());
}

Upvotes: 0

fmsf
fmsf

Reputation: 37137

When the click is triggered j will have value tours.length. You can lock the loop value, as well as the rest of the variables through closures.

for (var j=0; j<tours.length; j++){
  (function(){ 
    var currentJValue = j;
    var name = tours[currentJValue].name;

    var $tourLI = $('<li id="'+name+'"></li>');
    var $tourButton = $('<div class="button-inside"><span>'+name+'</span><span></span></div>');

    $tourButton.click(function() {
        alert(name);
    }
  })();
}

Upvotes: 0

Related Questions