0

I have a button, #add, which when clicked adds a row into a table. The last cell of the newly inserted row has a delete icon which if clicked I would like to remove the row.

I believe I'm 95% of the way there but for when clicking the delete icon nothing happens? Would this be due to the DOM needing a refresh?

$(document).ready(function(){
    $('#add').click(function() {
        $('tbody').append("<tr><td>test</td><td></td><td data-editable='true'>1</td><td><center><i id='delete' class='fa fa-trash-o'></i></center></td></tr>");
        $('#table').editableTableWidget();
    });
    $('#delete').click(function(){
        $(this).closest('tr').remove();
        console.log('click');
    })
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
rob
  • 149
  • 2
  • 11

1 Answers1

2

There are some mistakes in your code.

  1. You are duplicating the id. You shouldnt do that. You need to use class instead of it.
  2. Since you are creating the rows dynamically, normal click events wont work. you need to use event delegation for that.

Then your final code will be look like,

$('#add').click(function () {
    $('tbody').append("<tr><td>test</td><td></td><td data-editable='true'>1</td><td><center><i  class='fa fa-trash-o delete'></i></center></td></tr>");
    $('#table').editableTableWidget();
});
$('#table').on('click', '.delete', function () {
    $(this).closest('tr').remove();
    console.log('click');
})
David
  • 208,112
  • 36
  • 198
  • 279
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53