В таблице данных есть столбец с флажком id="sel_customer", ссылающийся на идентификаторы клиентов с несколькими строками.
Запрос Ajax (данные) возвращает строку с список идентификаторов клиентов, которых я хочу выбрать при загрузке таблицы данных.
Как я могу установить флажок sel_customer таблицы данных в соответствии со списком идентификаторов, возвращаемых через Ajax?
ПРИМЕЧАНИЕ: иногда он вводит $(".sel_customer").each(function (i, el) {, но в большинстве случаев он игнорирует эту функцию.
Как можно Я отмечаю только флажок с идентификаторами таблицы данных в соответствии со строкой идентификаторов через запрос Ajax?
Datatable - при загрузке таблицы данных отметьте флажок идентификаторов в соответствии с идентификаторами данных Ajax.< /p>
Customers.php
Код: Выделить всё
SEL
ID
NAME
Check all
Add customer checked
Код: Выделить всё
customer.datatable = $('#table1').DataTable({
...datatable,
ajax: 'Customer.php',
cache: false,
columns: [{
orderable: false,
data: null,
render: function(data) {
return ``;
}
},
{
data: 'id',
},
{
data: 'name',
},
]
});
//Customers
$.ajax({
method: 'post',
url: '../Rota.php?send=customers
data: '',
dataType: 'html',
success: function(data) {
// return 5,6,7,8 (returns list of IDs)
data = JSON.parse(data);
//data = '5,6,7,8';
if(data.length > 0) {
alert(data); //5,6,7,8
$(".sel_customer").each(function (i, el) { //It seems to ignore and not enter the function
//I think this line brings the Datatable IDs, here is the code snippet to correct
let vtr = $(this).closest("tr");
let vid = [vtr.find('td').eq(1).html()]; //get the datatable ID
if(vtr.find('td').eq(1).html() == 5) {//If id = 5, mark the row in the datatable
$(this).prop("checked", true);// this doesn't work
}
}).promise().done(function () {
//It works but it only brings the last record of .each, I need them all
});
}
//return;
},
error: function(data, textStatus, errorThrown) {
console.log('An error ocurred');
console.log(textStatus);
console.log(errorThrown);
}
});
/*** FROM HERE ON THE CODE IS OK ***/
/*** Check all Datatable checkboxes ***/
var marcar_tudo = true;
var json = [];
var lista_inserir = [];
var itens = '';
$("#selecionar_tudo").click(function () {
let checked = true;
if(!marcar_tudo) {
checked = false;
} else {
checked = true;
}
$(".sel_customer").each(function (i, el) {
$(el).prop("checked", checked);
})
btnInserirTodos()
if(!marcar_tudo) {
marcar_tudo = true;
$(this).html("Check All")
} else{
marcar_tudo = false;
$(this).html("Uncheck All")
}
})
customer.datatable.on('change', '.sel_customer', function () {
btnInserirTodos()
})
function btnInserirTodos() {
//zerar array
lista_inserir = [];
let total = 0;
$(".sel_customer").each(function (i, el) {
if($(el).is(":checked")) {
let tr = $(el).closest("tr");
let id = [tr.find('td').eq(1).html()];
lista_inserir.push(id);
total++;
}
})
//Transformar array em string
itens = lista_inserir.toString();
if(total > 0) {
if(total == 1) {
$("#insere_selecionados").prop("disabled", false).html(`Add ${total} customer`);
} else {
$("#insere_selecionados").prop("disabled", false).html(`Add ${total} customers`);
}
} else {
$("#insere_selecionados").prop("disabled", true).html("Add customer");
}
}
$("#insere_selecionados").click(function () {
let json = {
ids: itens
};
Swal.fire({
icon: "success",
title: "Your work has been saved",
showConfirmButton: false,
timer: 1500
});
$("#insere_selecionados").prop("disabled", true).html("Inserting...");
return;
$.ajax({
method: 'POST',
url: 'Rota.php?action=insert',
data: json,
dataType: 'html',
success: function(data) {
//data = JSON.parse(data);
//alert(data);
if(data == 'Inserted successfully') {
$("#table1").DataTable().ajax.reload();
}
$("#insere_selecionados").prop("disabled", true).html("Add customer")
},
error: function(data, textStatus, errorThrown) {
console.log('An error ocurred');
console.log(textStatus);
console.log(errorThrown);
}
})//Ajax
})
Подробнее здесь: https://stackoverflow.com/questions/791 ... a-string-o