Gorgon_Union Gorgon_Union - 6 months ago 18
Javascript Question

on.click not working after first click on dynamically created table

I dynamically create a table full of links of 'actors', which allows to pull the actors information into a form to delete or update the row. The delete button only pops up when you select an actor.

I'm able to click a row, pull the information into the forms, and delete it on first try. However when I attempt to add a new 'Actor' and then delete it, or just delete an existing 2nd row, the button 'Delete Actor' doesn't work. It's only after the first successful delete does the button no longer work.

var addActor = function() {
// Creates a table of links for each added actor with an id based from # of actors
$("#actorsTable").append("<tr><td><a href='' onclick='deleteActor(this)' class='update' data-idx='" + actors.length + "'>" + newActor.fName + " " + newActor.lName + "</a></td></tr> ");

$(".update").off("click");
$(".update").on("click", selectActor);
};


var deleteActor = function(e) {
$("#deleteActor").on('click', function(event) {
event.preventDefault();
var row = e.parentNode.parentNode;
row.parentNode.removeChild(row);
clearForm(actorForm);
actorState("new");
});
};


I'm new to jQuery/javascript, and I'm pretty sure its due to the change in DOM, but I just don't know what to change to make it work.

Here is an Example of it in action

Answer

Try

var deleteActor = function(e) {

$("#deleteActor").unbind();
$("#deleteActor").on('click', function(event) {
    event.preventDefault();
    var row = e.parentNode.parentNode;
    row.parentNode.removeChild(row);
    clearForm(actorForm);
    actorState("new");
});

};

Here is the link for unbind. http://api.jquery.com/unbind/