我有一个带有复选框插件的服务器端数据表设置。 每个复选框都有一个product_id的数据。
var table = $('#display_users').DataTable( {
"processing": true,
"serverSide": true,
'ajax': '{{ route ('/getUsers') }}',
'columns' : [
{"data" : "product_id"},
{"data" : "product_id"},
{"data" : "first_name"},
{"data" : "last_name"},
{"data" : "email"},
{"data" : "company"},
{"data" : "department"},
{"data" : "created_at"}
],
'columnDefs': [
{
'targets': 0,
'checkboxes': {
'selectRow': true
},
我希望能够在选中一个复选框后,选中所有具有相同product_id的复选框。这仅对于当前所选页面上的记录是必需的。 似乎可以通过选择api复选框来实现,但是到目前为止我还没有成功
答案 0 :(得分:2)
我认为'checkbox'插件没有太大价值,因为它的功能可以通过几行代码轻松实现,同时还可以提供更大的灵活性。
但是,由于您所需的功能可以通过本机DataTables API轻松编码,因此您实际上并不需要深入研究“复选框”插件内部。
//listen for the clicking first column checkboxes
$('#display_users').click('tbody td:eq(0) [type="checkbox"]', function(){
//grab current checkbox state and criteria to match (product_id) from the row data
const state = $(event.target).prop('checked');
const productId = dataTable.row($(event.target).closest('tr')).data().product_id;
//iterate through current page rows and adjust checkboxes upon matching product_id
dataTable.rows({page:'current'}).every(function(){
if(this.data().product_id == productId) $(this.node()).find('td:eq(0) [type="checkbox"]').prop('checked', state);
});
});
完整填写此概念的演示,您可能会在下面找到
:
//data sample
const srcData = [
{product_id: 7, first_name: 'Nick', last_name: 'Furry', company: 'Avengers Inc'},
{product_id: 7, first_name: 'Steve', last_name: 'Rogers', company: 'Avengers Inc'},
{product_id: 4, first_name: 'Arthur', last_name: 'Curry', company: 'Justice Ltd'},
{product_id: 4, first_name: 'Clark', last_name: 'Kent', company: 'Justice Ltd'},
{product_id: 4, first_name: 'Barry', last_name: 'Allen', company: 'Justice Ltd'}
];
//datatable initialization
const dataTable = $('#display_users').DataTable({
dom: 't',
order: [1, 'asc'],
data: srcData,
columns: [null, ...Object.keys(srcData[0])].map(header => ({title: header || '', data: header})),
columnDefs: [
{targets: 0, orderable: false, render: () => '<input type="checkbox"></input>'}
]
});
//essential part - row checkbox click hander
$('#display_users').click('tbody td:eq(0) [type="checkbox"]', function(){
//grab current checkbox state and criteria to match (product_id)
const state = $(event.target).prop('checked');
const productId = dataTable.row($(event.target).closest('tr')).data().product_id;
//iterate through current page rows and adjust checkboxes upon matching product_id
dataTable.rows({page:'current'}).every(function(){
if(this.data().product_id == productId) $(this.node()).find('td:eq(0) [type="checkbox"]').prop('checked', state);
});
});
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="display_users"></table>
</body>
</html>