datatable動態生成複選框
阿新 • • 發佈:2019-02-10
首先需要說明:
1,原始的datatable是沒有複選操作和批量操作的
2,當用戶點選批量的時候做了非空判斷,然後選中後再將選中的資料id以連結的方式傳遞到下一個頁面
3,整個頁面是jsp格式
<a href="javascript:void(0);" id="btnAll">批量編輯</a>
<table class="table table-striped table-bordered table-hover dataTables-example" id='table'>
<thead class='head'>
<tr>
<th class='th'>
<input type="checkbox" class="checkall" />
</th>
<th>序號</th>
<th>裝置編號</th>
<th>場所</th>
<th >裝置型號</th>
<th>線上</th>
<th>狀態</th>
<th>最後一次啟動</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr data-id ="${equipment.id}">
<td></td>
<td>${equipment.id}</td>
<td>${equipment.equipmentNum}</td>
<td>${equipment.siteName}</td>
<td>${equipment.equipmentType}</td>
............
</tr>
</tbody>
</table>
這裡有一個問題關鍵點,如果列表的checkbox不是動態生成,很有可能,當用戶點選第二頁的頭部全選的時候,會直接跳轉到第一頁的資料.
//動態生成複選框
var table = $('#table');
table.DataTable({
"fnDrawCallback": function() {
$(this).find('thead input[type=checkbox]').removeAttr('checked');
},
"aoColumnDefs": [{
'targets': 0,
'searchable':false,
'orderable':false,
'className': 'dt-body-center',
'render': function (data, type, row){
return '<input class="checkchild" type="checkbox"/>';
}
}]
})
//datatable全選
$('.checkall').on('click', function () {
if (this.checked) {
$(this).attr('checked','checked')
$('.checkchild').each(function () {
this.checked = true;
});
} else {
$(this).removeAttr('checked')
$('.checkchild').each(function () {
this.checked = false;
});
}
});
//批量處理資料
$('#btnAll').on('click',function(){
var selectLoans = [];
$('.checkchild').each(function () {
if($(this).is(':checked')){
selectLoans.push($(this).parent().parent().attr('data-id'));
}
});
if(selectLoans.length == 0){
layer.msg('請至少選中一項進行操作');
$("#btnAll").attr("href",'javascript:void(0);');
}else{
var idListStr ='';
for (var i = 0; i < selectLoans.length; i++) {
if(i!=selectLoans.length-1){
idListStr = idListStr + selectLoans[i] +",";
}else{
idListStr = idListStr + selectLoans[i];
}
}
$("#btnAll").attr("href",'equipment/batchUpdate.do?idListStr='+idListStr);
}
});