Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery click event not working for dynamic fields [duplicate]

Possible Duplicate:
jQuery - Click event doesn’t work on dynamically generated elements

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 = '<tr><td><input id="column_0" name="column[0]" style="width:40%;" type="text" /> <img alt="Delete-icon24x24" class="btnDel clickable" id="" src="/assets/delete-icon24x24.png" /></td></tr>';
        $('#columns').append(newTr);
    });

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

    row.remove();
});
like image 767
Sean Avatar asked Jan 16 '13 04:01

Sean


1 Answers

use on()

$(document).on('click', '.btnDel', function(){
  //your code
})
like image 141
Kanishka Panamaldeniya Avatar answered Oct 07 '22 15:10

Kanishka Panamaldeniya