Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using up/down keys to move between text fields in a table

I have a <table> that is set up roughly like this

Name            Description     Notes
===========================================
[___________]   [_________]     [_________]

There are quite a few rows and rather than the users tabbing through rows, I'd like to implement pressing the Up/Down keys to move up and down in the selected column.

The rows have the ID 'row_{ID}' where ID is the database ID. The fields have the ID 'name_{ID}', 'description_{ID}', 'notes_{ID}' etc.

I'm trapping the press with jQuery like:

$('input[id^="name_"]').bind('keyup', function(e) {

    if(e.keyCode == 38)
        ...
    else if(e.keyCode == 40)
        ...
});

Essentially I want, if the user is in row 2 of the description and press up, that they move to row 1 description field, and if they press down they move to row 3 description field.

I can't work out the way to select the next or previous rows. Can anyone provide assistance?

like image 807
Sam Avatar asked Mar 29 '26 03:03

Sam


1 Answers

To go down:

$(this).closest('tr').next().find('input[name=' + $(this).attr('name') + ']').focus();

To go up:

$(this).closest('tr').prev().find('input[name=' + $(this).attr('name') + ']').focus();

That is, assuming your inputs are all named the same.

Otherwise, you'll have to change that selector a bit, or use jQuery's .index() on the td and then select with .eq().

like image 150
Joseph Silber Avatar answered Apr 02 '26 02:04

Joseph Silber