JQuery DataTable Keydown

I'm having trouble capturing keydown events using the jQuery DataTable. My goal is to allow users to navigate through the rows of the table using the arrow keys. So I would like to catch keydown events and move the selected row of the table (this is what I track outside the data using the class for the selected row) when the user presses the arrow key. However, I do not seem to catch the keydown events.

For example, the code below does not work:

$('#myTable tbody').keydown(function (event){...});

My thought is that the problem in the table has no focus, but maybe this is the wrong way. For example, even if I add the following, I will not catch keydown events with the above code:

 $('#myTable tbody').click(function(e){ $('#myTable tbody').focus();});

I can catch keydown with $ (document), but this is not desirable.

Thank.

+5
1

... ( , , ), :

http://jsfiddle.net/BLSully/Xdkea/

"" tabindex, "". , "-", keypress .

<table id="myTable" tabindex=0>
    <tbody>
        <tr><td>Row 1</td></tr>
        <tr><td>Row 2</td></tr>
        <tr><td>Row 3</td></tr>
        <tr><td>Row 4</td></tr>
        <tr><td>Row 5</td></tr>
    </tbody>
</table>

JavaScript:

$(function(){
    var focusedRow = null;
    $('#myTable').on('keydown', function(ev){
        console.log(ev.keyCode);
        if(focusedRow == null) {
            focusedRow = $('tr:nth-child(1)', '#myTable');
        } else if(ev.keyCode === 38) {
            focusedRow.toggleClass('focused');
            focusedRow = focusedRow.prev('tr');
        } else if(ev.keyCode === 40) {
            focusedRow.toggleClass('focused');
            focusedRow = focusedRow.next('tr');
        }
        focusedRow.toggleClass('focused');
    });
    $('#myTable').focus();
});
+6

All Articles