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?
$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:
Note:
varis used above to control scope.Also, you don’t need to use
each()for this. This is equivalent: