0

I want to fade out a set of div's based on the ajax response. This code isn't doing what I wanted.

What am I doing wrong?

$('.view_result').click(function() {
    $('.result_bar').fadeIn();
    var set = $('.result_bar');
    for(var i = 0; i < set.length; i++) {
        $.post('get_votes.php', {'id':$(set[i]).attr('name')}, function(data) {
            $('.result_bar')[i].fadeOut(); //--> Didn't Work
            $(set)[i]).fadeOut(); //--> Didn't Work
            set[i].fadeOut();// --> Didn't Work
        }); 

    }
return false;
});
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
Praveen
  • 2,400
  • 3
  • 23
  • 30
  • The variable i will always be set to set.length - 1 in the post success function. Take a look at this: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Gruff Bunny Sep 22 '13 at 09:05
  • Thanks, but $(set[0]).fadeOut() doesn't work too... – Praveen Sep 22 '13 at 09:07
  • Are you sure? Your original code snippet has brackets in the wrong place for all 3 calls to fadeOut. – Gruff Bunny Sep 22 '13 at 09:18

1 Answers1

2

The problem is the usage of closure variable i in the callback function.

In your case since set is a jQuery wrapper, you can use the .each() to iterate instead of using the for loop

$('.view_result').click(function () {
    $('.result_bar').fadeIn();
    var set = $('.result_bar');

    set.each(function(idx, el){
        $.post('get_votes.php', {
            'id': $(el).attr('name')
        }, function (data) {
            $(el).fadeOut(); //--> Didn't Work
        });
    })
    return false;
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531