Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use jQuery to reassign the tab-order from horizontal to vertical in a table?

Tags:

jquery

How can I use jQuery to set up the tabbing order of a table with input elements so that the tab-order will be vertical (down each of the columns) instead of the default horizontal method?

The numbers below represent the tabbing order I would like. I'd the jQuery code to work independently of the number of rows and columns in the table.

Example Table (rendered as an image unfortunately)

Picture 1.png http://img263.imageshack.us/img263/9125/picture1pjf.png

Example table HTML Code:

<table>
 <tr>
  <td><input type="text" /></td> <!-- 1 -->
  <td><input type="text" /></td> <!-- 4 -->
  <td><input type="text" /></td> <!-- 7 --> 
 </tr>
 <tr>
  <td><input type="text" /></td> <!-- 2 -->
  <td><input type="text" /></td> <!-- 5 -->
  <td><input type="text" /></td> <!-- 8 -->
 </tr>
 <tr>
  <td><input type="text" /></td> <!-- 3 -->
  <td><input type="text" /></td> <!-- 6 -->
  <td><input type="text" /></td> <!-- 9 -->
 </tr>
</table>
like image 833
cwd Avatar asked Dec 27 '11 04:12

cwd


People also ask

How do I change the order of tabs in HTML?

The tabindex attribute specifies the tab order of an element (when the "tab" button is used for navigating). The tabindex attribute can be used on any HTML element (it will validate on any HTML element.


1 Answers

Here's one way to do it:

$(function() {

    $('tr').each(function() {
        // For each row

        $(this).find('td').each(function(i) {
            // For each cell in that row (using i as a counter)

            $(this).find('input').attr('tabindex', i+1);
            // Set the tabindex of each input in that cell to the counter

        });
        // Counter gets reset for every row
    });
});

What this achieves is something like this:

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

So that by tabbing, you first go through all the ones, then all the twos, and so on.

Example: http://jsfiddle.net/grc4/G5F7S/3/

EDIT:

To avoid the problem when there are other input fields, you can simply add an offset to each tabindex. This won't always get the order perfect, but it's better than nothing.

The updated example is here: http://jsfiddle.net/grc4/G5F7S/6/

like image 75
grc Avatar answered Sep 21 '22 12:09

grc