Sunday, December 2, 2018

javascript - jquery click event not working for dynamic fields











I just have a clickable add button that adds new table rows. The table rows include a delete button. I've noticed that when I dynamically add a new row the button does not fire the click event, but if the button exists when the page loads, then it works fine. How can I correct this?



Javascript:




$('#btnAdd').click(function () {

var newTr = ' Delete-icon24x24';
$('#columns').append(newTr);
});

$('.btnDel').click(function () {
alert('hey');
console.log('test');
var row = $(this).closest("tr");

alert(row);

row.remove();
});

Answer



You'll need to use event-delegation:



$("table").on("click", ".btnDel", function () {
/* Respond to click here */

});


The reason is that you cannot bind a handler to items that don't presently exist in the DOM. You can, however, bind a handler to a delegate target (a parent element that will remain in the DOM). Clicks will bubble up the DOM, eventually reaching the delegate target.



We listen for clicks on the table and we evaluate whether they came from an .btnDel element. This will now respond to clicks from .btnDel elements loaded when the page loaded, as well as those that are added dynamically later.



Lastly, don't re-use ID values.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...