I have ajax request and when the ajax success I’m replacing the content using html from the ajax response.
The controller is like this:
$html = view('payroll-cutoff.data-attendance-group', compact('payroll_group', 'payroll_cutoff_group'))->render();
return response()->json([
'success' => true,
'data' => $html,
]);
Inside ajax success, I have some code to manipulate the view. But somehow after I successfully replacing the html content of tbody
, the jquery event not working anymore even though when I inspect the element I successfully replacing the content using html from ajax response.
success:function(response){
// thisObj = '.process-attendance'
let element = response.data;
let el_data = $(element).filter('.group-payroll').find('.body-component').html();
thisObj.closest('table').find('tbody').html(el_data);
// code bellow not working
thisObj.closest('table').find('thead').addClass('done-group');
thisObj.closest('table').find('tbody').addClass('done-group');
},
For example is I have this on click function, but it’s not working anymore after ajax success.
$(".show-emp").click(function () {
showEmployee($(this));
});
function showEmployee(el)
{
$(el).closest('tbody').find('.employee').toggle();
$(el).closest('tbody').find('.employee-head').toggle();
}
And this is the view:
<table class="table group-payroll">
<thead class="head-component">
<tr>
<th colspan="7"></th>
</tr>
</thead>
<tbody class="body-component">
<tr>
<td style="width: 100%" colspan="7">
<a href="javascript:void(0)" class="btn btn-sm mb-2 checkall process-attendance">Process Attendance</a>
<a href="javascript:void(0)" class="btn btn-sm mb-2 checkall me-5 show-emp"></a>5 Employee
</td>
</tr>
<tr class="employee-head" style="display: none">
<td>No</td>
<td>Name</td>
<td>HK</td>
<td>IN</td>
</tr>
<input type="hidden" class="process-done" value="">
<input type="hidden" name="employee_id[]" class="employee_id" value="">
<tr class="employee" style="display: none">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
2
Answers
Let me know if the below’s code work
Check out the jquery documentation. There are two types of event handlers, direct and delegated. This is a delegated event handler.
Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time.
in your case that HTML added to the table after success is descendent elements.
You need to try like below snippet.
Helpful Links:
https://api.jquery.com/on/
https://api.jquery.com/click/