jQuery DataTables: How to navigate rows with KeyTable plugin - Solution 2
Example for article at https://www.gyrocode.com/articles/jquery-datatables-how-to-navigate-rows-with-keytable-plugin/
by gyrocode
HTML
<link rel="stylesheet" href="https://cdn.datatables.net/v/dt/dt-1.10.16/kt-2.3.2/sl-1.2.3/datatables.min.css">
<script src="https://cdn.datatables.net/v/dt/dt-1.10.16/kt-2.3.2/sl-1.2.3/datatables.min.js"></script>
<h3><a target="_blank" href="https://www.gyrocode.com/articles/jquery-datatables-how-to-navigate-rows-with-keytable-plugin/">jQuery DataTables: How to navigate rows with KeyTable plugin</a> <small>Solution 2</small></h3>
<p><b>Details:</b> <span id="example-console">N/A</span></p>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
CSS
table.dataTable th.focus,
table.dataTable td.focus {
outline: none;
}
JavaScript
$(document).ready(function (){
var table = $('#example').DataTable({
ajax: 'https://gyrocode.github.io/files/jquery-datatables/arrays.json',
select: {
style: 'single'
},
keys: {
keys: [ 13 /* ENTER */, 38 /* UP */, 40 /* DOWN */ ]
}
});
// Handle event when cell gains focus
$('#example').on('key-focus.dt', function(e, datatable, cell){
// Select highlighted row
table.row(cell.index().row).select();
});
// Handle click on table cell
$('#example').on('click', 'tbody td', function(e){
e.stopPropagation();
// Get index of the clicked row
var rowIdx = table.cell(this).index().row;
// Select row
table.row(rowIdx).select();
});
// Handle key event that hasn't been handled by KeyTable
$('#example').on('key.dt', function(e, datatable, key, cell, originalEvent){
// If ENTER key is pressed
if(key === 13){
// Get highlighted row data
var data = table.row(cell.index().row).data();
// FOR DEMONSTRATION ONLY
$("#example-console").html(data.join(', '));
}
});
});