0

I'm trying to simply delete the closest li.

It works if I simply do: <li><a id="delete-hello">Teste</a></li>

There is no errors in the console. The problem is that my li is generated then the user does something (in this case when clicks a button) Because of that the method is never triggered and li never dissapears.

How my $("a[id^='delete-']").click(function() can run after the li is generated?

$(document).ready(function() {

  //delete testCase row when click delete button
  $("a[id^='delete-']").click(function() {
    console.log('clicked');
    $(this).closest('li').remove();
  });

  var table = $('#dataTable').DataTable({
    buttons: [{
      text: 'Add test case(s)',
      action: function() {
        var testCaseName;
        var data = table.rows({
          selected: true
        }).data();
        console.log(data);
        $.each(data, function(index, value) {
          console.log(value[1]);
          testCaseName = value[1];
          $('#testCaseList').append('<li class="list-group-item justify-content-between">' + testCaseName + '<a class="action-icon" id="delete-' + testCaseName + '" name="' + testCaseName + '"><span class="fa fa-trash"></span></button></li>')
        });
      }
    }]
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">


<ul id="testCaseList" class="list-group"></ul>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
sdadsa
  • 69
  • 6

1 Answers1

3

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

Since your elements are added to the DOM dynamically you need to use the event delegation on() instead :

$("body").on('click', "a[id^='delete-']", function() {
    console.log('clicked');
    $(this).closest('li').remove();
});
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • lol that was fast. Is this that easy? I've been stuck for hours.Can you explain please? – sdadsa Jan 04 '18 at 16:37
  • On dynamically generated, or numerous elements, it's best to put one event handler on a parent element, rather than each element having their own. This also allows your usage too. – Nick Jan 04 '18 at 16:38
  • **omg that works perfectly.** never knew of this. – sdadsa Jan 04 '18 at 16:39