I have a JS function here that I'm trying to fix. This function gets triggered when the Check All button is clicked. When this button is clicked, all the items in the table should be checked and disabled. When I run this function and click the Check All button, all the items are selected briefly and then they go back to being unchecked. What am I doing wrong?
PS: I've tried adding e.preventDefault() and the end of the function and it doesn't work
$(document).ready(function () {
$('body').on('change', '#checkAll', function (e) {
if(this.checked){
let boxes = $("input.promo-action-checkbox");
boxes.toArray().forEach(element => {
console.log(element);
$(element).attr('disabled', 'disabled');
var name = $(element).data('name');
var number = $(element).data('number');
var user = $(element).data('user');
$.ajax({
method: 'post',
url: '/checker',
contentType: "application/json",
data: JSON.stringify({
name: name,
number: number,
user: user
}),
dataType: 'json',
error: function () {
$(element).attr('disabled', '');
}
})
});
How columns are made in html table:
var table = $('#datatable').DataTable({
pageLength: 20,
lengthChange: false,
language: {
paginate: {
previous: '<i class=\'fas fa-angle-left\'>',
next: '<i class=\'fas fa-angle-right\'>'
}
},
ordering: true,
processing: true,
serverSide: true,
ajax: {
url: '/table/',
dataSrc: 'results'
},
columns: [
{
data: null,
render: function (data, type, row, meta) {
let rowHtml = '<div class="custom-control custom-checkbox mb-3"> <input class="custom-control-input promo-action-checkbox" id="checkbox-' + meta.row + '" data-name="' + row.name + '" data-phone="' + row.number + '" data-admin="' + row.user + '" type="checkbox"'
if (row.fulfilled) {
rowHtml += ' disabled checked'
}
rowHtml += '> <label class="custom-control-label" for="checkbox-' + meta.row + '"></label></div>'
return rowHtml
}
},
{
searchable: true,
data: 'name'
}
]
});
Here is what works however the "checkAll" box does not get ticked. Also this table is not inside a form.
$('#checkAll').click(function (e) {
e.preventDefault()
$('input.action-checkbox').prop('checked', this.checked);
$('input.action-checkbox').prop('disabled', true);
return false;
})
Table Structure:
<div class="table-responsive">
<table class="table align-items-center table-flush table-striped" id="datatable-promo-code">
<thead class="thead-light">
<tr>
<th>Check All <input id = "checkAll" type= "checkbox"></th>
<th>Name</th>
<th>Info</th>
<th>address</th>
<th>Email</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>