2
votes

I have a large HTML table with dynamically added rows.

The table has a standard structure (incl. thead, tbody and tfoot).

Within this table there are editable TDs (which have the class "editable" and contain a contenteditable div) and non-editable TDs (which dont't have the class "editable" and do not contain a div).

I am trying to create a custom arrow key navigation that allows me to jump from one editable TD to next or previous one (like in an Excel table).

To test this I used the below example but this only works partially, i.e. the alerts are shown correctly but I am not able to do anything with the corresponding div (e.g. change its background or add a text etc.).

Can someone tell me what I am doing wrong here ?

My jQuery (in doc ready):

$(document).keydown(function(e){
    switch(e.which){
        case 37: // left arrow
            alert('test left');
            $(this).closest('td').prevUntil('td.editable').find('div').text('test');
            break;
        case 39: // right arrow
            alert('test right');
            $(this).closest('td').nextUntil('td.editable').find('div').text('test');
            break;
        default: // exit for other keys
            return;
    }
    e.preventDefault(); // prevent default action
});

My HTML (example row):

<tr>
    // ...
    <td class="editable"><div contenteditable="true"></div></td> <!-- editable -->
    <td class="editable"><div contenteditable="true"></div></td> <!-- editable -->
    <td></td> <!-- non-editable -->
    <td></td> <!-- non-editable -->
    <td class="editable"><div contenteditable="true"></div></td> <!-- editable -->
    // ...
</tr>
1
Please see "Should questions include “tags” in their titles?", where the consensus is "no, they should not"!user57508

1 Answers

1
votes

this in your code refers do document not single element

if you use $(e.target) you can get single element

Also you should use next() function instead of nextUntil()

$(e.target).closest('td').nextAll('td.editable:first').find('div').text('test');