tags:

views:

409

answers:

2

I am building a list with checkboxes, after the list is created I am using ".each" to go through them all and trying to apply a click procedure.

My code like this works fine:

$.ajax({
 url: "./views/todoitems.view.php",
 data: "cmd=list",
 success: function(html){
  $('#list-container').empty().append(html);
  $('input:checkbox').each(function(){
   $check = $(this);
   $check.click(function(){
    alert($(this).attr('itemid'));
   });
  });
 }
});

However, as soon as I change the alert to be

alert($check.attr('itemid'));

It only ever shows the id of the last item in the list no matter which one is clicked. What am I doing wrong?

+3  A: 

$check is set inside the each handler and is a global variable. That means it'll retain the last value set, being the last checkbox. You need to set it inside the click handler if you want to do it right. Change it to:

$.ajax({
  url: "./views/todoitems.view.php",
  data: "cmd=list",
  success: function(html) {
    $('#list-container').empty().append(html);
    $('input:checkbox').each(function(){
      $check.click(function() {
        var $check = $(this);
        alert($check.attr('itemid'));
      });
    });
  }
});

Note: var is used above to control scope.

Also, you don't need to use each() for this. This is equivalent:

$.ajax({
  url: "./views/todoitems.view.php",
  data: "cmd=list",
  success: function(html) {
    $('#list-container').empty().append(html);
    $('input:checkbox').click(function() {
      alert($(this).attr('itemid'));
    });
  }
});
cletus
+2  A: 

To add to cletus' answer (I can't comment yet) $check is becoming an implied global variable because its declaration is missing var.

BStruthers