1

I have a dynamically generated table. Something like this:

<thead>
<tr>
<th>Task</th>
<th>options</th>
</tr>
</thead>
<tbody id="tasks-list">
@foreach($tasks as $task)
<tr id="contact_{{$contact->id}}">
<td>{{task->name}}
 <td><button class="btn btn-warning btn-xs btn-detail open-modal" value="{{$contact->id}}">Edit</button>
<button class="btn btn-danger btn-xs btn-delete delete-task" value="{{$contact->id}}">Delete</button></td>
</tr>
@endforeach
 </tbody>
</table>

Then I have a button to add a new task with AJAX.

When it succesfully adds a task, a new row with the recently created info gets appended:

 var task = '<tr id="contact_' + data.id + '">' +'<td>' + data.name + '</td>' +
'<td><button class="btn btn-warning btn-xs btn-detail open-modal" value="' + data.id + '">Editieren</button><div style="margin-left: 3px"' +
'<button class="btn btn-danger btn-xs btn-delete delete-task" value="' 
+ data.id + '">Löschen</button></td></tr>';

 $('#tasks-list').append(task);

This works fine. Everything is appended correctly and the buttons have the same propeties as the generated by Blade. Ids are also correct, there is no difference. When I click on edit or delete, I get no response. Not even an error in the console. When I refresh the site the buttons work so the stored information is actually correct.

Any help would be appreciated.

EDIT: Handler

   $('.delete-task').click(function(){
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        })
        var task_id = $(this).val();

        $.ajax({
            type: "DELETE",
            url: '/task_edit/' + task_id,
            success: function (data) {
                console.log(data);
                $("#contact_" + contact_id).remove();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });
prgrm
  • 3,734
  • 14
  • 40
  • 80

1 Answers1

1

You can't do this using that way, you have to use delegation.

Example

$(document).on('click','.delete-task',function(){
    //your business here
}); 

or use delegate and this is a similar question jQuery click function doesn't work after ajax call?

Community
  • 1
  • 1
Moustafa Elkady
  • 670
  • 1
  • 7
  • 17