Adding and removing DIV-IDs from an array
Hi,
I have a number of DIVs that I want to make 'selectable' on click, which means that I give the DIV you click on a class (just to show it's selected) and save its ID into an array. When I click on that DIV again, the class should be removed and its ID should be removed from the array as well. My code goes like
-
var selected_items = new Array();
$(".selectableDivs").click(function() {
if($(this).hasClass("selected")) {
$(this).removeClass("selected");
selected_items = jQuery.grep(selected_items, function (a) {
return a != $(this).attr("id");
});
} else {
$(this).addClass("selected");
selected_items.push($(this).attr("id"));
}
alert(selected_items);
}
But the alert at the end of the code always shows my a list of all divs I ever selected, even those that I unselected again. The IDs are just not removed from the array. Does anyone have an idea? Is that maybe because items saved in the array are not exactly $(this).attr("id") anymore?
Thanks,
Luke