Reputation: 3
I have a quantity of rows:
var goal_index = 2;
And I have a function, which create some rows (Default 2 rows) with two buttons: Trash (remove row), add(adding anoter row).
// Creating Goals
var goals_creating = function(){
var goals_area = $('.goalsArea'),
add_button = $('<span class="add_btn"></span>'),
trash_button = $('<span class="trash_btn"></span>');
goals_area.html('');
for(var i = 0, j = 1; i < goal_index; i++, j++ ){
goals_area.append(
'<div class="row" data-trashgoal = ' + i + '>' +
'<div class="col-lg-1">' +
'<span class="trash_btn" data-trashgoal = ' + i + '></span>' +
'</div>' +
'</div>'
);
}
// Last trash tag
var last_trash_btn = $('.trash_btn').last();
// Insert after last trash button
last_trash_btn.after(add_button);
};
In last part of function, I insert button (add) to last row. And after that running my function:
goals_creating();
After running, I created two events to two buttons (Add) and (Remove):
$('.add_btn').on('click', function(){
goal_index++;
goals_creating();
});
$('.trash_btn').on('click', function(){
var goal_to_del = $(this).data('trashgoal');
$('.row[data-trashgoal="' + goal_to_del + '"]').remove();
goal_index--;
goals_creating();
});
But, they are working one time, after that buttons stay non active, and not working. How can I fix this bug? Thanks
Upvotes: 0
Views: 68
Reputation: 413757
You have to use event delegation. Events "bubble" up the DOM, and jQuery makes it easy to exploit that:
$(document).on('click', '.add_btn', function() { /* as before */ });
$(document).on('click', '.trash_btn', function() { /* as before */ });
By doing that, you're saying, "When a 'click' event reaches the top of the DOM, and it came from an element that matches class 'add_btn', do this stuff." Because you've installed just that one handler at the top of the DOM, it won't go away and it'll catch those events from elements that were there from the beginning as well as from elements added later.
The value of this
will be set for you exactly as it would be in an event handler set up directly on an element.
Upvotes: 1