I have a delete button. When clicking on the button, I want to generate a second button to confirm that the user really wants to delete something. BUT: When clicking on the second button, the $('.deleteConfirmed').click(function() {
does not trigger.
I'm not exactly sure how JQuery works, but my guess is that this happens because the click listener was created before the second button existed, correct? If that is true, what would be a solution to make clicking the second button call deleteEntityConfirmed(id)
?
I guess you could probably do it with HTML's onclick
attribute on the second button, but does JQuery offer a more elegant solution for this scenario?
Here is some code showing my scenario, I tried to keep only relevant parts in.
HTML:
<button class="delete" data-id="5">
Delete
</button>
<div id="somewhere"></div>
JS:
$(function() {
$('.delete').click(function() {
var id = $(this).data('id');
$('#somewhere').empty().append('<button class="deleteConfirmed" data-id="' + id + '">I\'m sure I want to delete</button>');
});
$('.deleteConfirmed').click(function() {
alert("debug message"); // we don't get here when clicking the second button. It seems to not be listening to it
var id = $(this).data('id');
deleteEntityConfirmed(id);
});
});
function deleteEntityConfirmed(id){
// If we'd get here after clicking the second button, this would be full success
alert("Deleting id " + id);
}