I have two questions for jquery datatables :
This is my initialization of my DataTable:
ar dataTableOption = {"pageLength": 5,
"pagingType": "simple",
"info": false,
"searching": false,
"select": {
style: 'single'
},
"lengthChange": false,
"columnDefs": [
{
"targets": [0],
"visible": false,
"searchable": false
}
]
};
dataTable = $('#dataTable').DataTable(dataTableOption);
Thank you for your help in advance!
One of the ways:
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'tr', function () {
if($(this).hasClass( "selected" )){
//make sure it can't be unselected if there is just one selected row
if(table.rows('.selected').data().length > 1){
$(this).removeClass( "selected" );}
}
else{
$(this).addClass( "selected" );
}
} );
//To pre-select the first row
$('#example tbody tr:eq(0)').click();
} );
@ Harshul Pandav
Thank you for your post. Your proposed solution worked not 100% for me but it helped me a lot for finding a solution for my problems.
To select the first line worked this for me:
dataTable.row(':eq(0)', { page: 'current' }).select();
To get at least one line selected I use the user-select event, to remember my last selected column:
dataTable.on( 'user-select', function ( e, dt, type, indexes ) {
lastSelectedRow = dt.rows( '.selected' )[0][0];
});
After this, the click event passed through, if no row is selected anymore, the row with index of last selected row is selected:
dataTable.on( 'click', 'tr', function (evt) {
if (dataTable.rows( {selected:true} ).any() == false) {
dataTable.row(lastSelectedRow).select();
}
)};
For finding out the last selected row the deselect (dt.on( 'deselect', function ( e, dt, type, indexes ) ) event can also be used.
Prevent deselect of already-selected row:
myTable.on('user-select', function (e, dt, type, cell, originalEvent) {
if ($(cell.node()).parent().hasClass('selected')) {
e.preventDefault();
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.