Navigate form fields with arrow keys

Recently I created a puzzle game called Regex Crossword, where a lot of data is to be entered in a grid of input form fields. To improve a little on the user experience, I wanted to be able to navigate between fields using the arrow keys.

The following JavaScript snippet enables you to do just that, when you have a table containing input fields. I have wrapped it all as a jQuery plugin, to make it easy to use between projects.

(function ($) {
  $.fn.formNavigation = function () {
    $(this).each(function () {
      $(this).find('input').on('keyup', function(e) {
        switch (e.which) {
          case 39:
            $(this).closest('td').next().find('input').focus(); break;
          case 37:
            $(this).closest('td').prev().find('input').focus(); break;
          case 40:
            $(this).closest('tr').next().children().eq($(this).closest('td').index()).find('input').focus(); break;
          case 38:
            $(this).closest('tr').prev().children().eq($(this).closest('td').index()).find('input').focus(); break;
        }
      });
    });
  };
})(jQuery);

Example

You can check out the script in this live example:

ABC
1
2
3

Code is also available on GitHub.