Reputation: 161
I want to collect every id of div
that has been clicked then assign that value to a var
.
Here is my code:
$('div.kim2bb').on('click', function(){
var el = el + ', ' + $(this).attr('id');
alert(el);
});
I tried this one, but every time I click el
it's reset, how can I prevent it from resetting?
Upvotes: 0
Views: 60
Reputation: 5822
A further iteration of the answers given before is to test if an item has previously been added before
var ids=[];
$('div.kim2bb').on( 'click', function(){
var id = $(this).attr("id");
// if id has not been added before
if( ids.indexOf( id ) == -1 ) {
ids.push( id );
}
console.log( ids.join( "," ) );
});
Upvotes: 0
Reputation: 11371
Keep it in an array. Makes it easier to use later. (My opinion)
el=[];
$('div.kim2bb').on('click', function(){
el.push($(this).attr('id'));
console.log(el);
});
Upvotes: 2
Reputation: 1007
Move the initial declaration of el
outside of your click event:
var el = '';
$('div.kim2bb').on('click', function(){
el += ', ' + $(this).attr('id');
alert(el);
});
This causes the variable to live in another scope.
And you should use arrays instead:
var el = [];
$('div.kim2bb').on('click', function(){
el.push( $(this).attr('id') );
alert(el.join(", "));
});
Upvotes: 5