Thursday, February 9, 2012

Keyboard Navigation between Input Fields using JQuery

If you have a form with several input fields, one can easily add keyboard based navigation using JQuery. This means, that if the user is in the 1st input field and pushes the down key, the focus jumps to the next field, etc.

To achive this, we define two helper functions, which find the next or the previous instance for a given selected range:

jQuery.fn.elementAfter = function(other) {
    for(i = 0; i < this.length - 1; i++) {
        if (this[i] == other) {
            return
jQuery(this[i + 1]);
        }
    }
    return jQuery;
};

jQuery.fn.elementBefore = function(other) {
    if (this.length > 0) {              
        for(i = 1; i &lt; this.length; i++) {
            if (this[i] == other) {
                return
jQuery(this[i - 1]);
            }
        }
    }
    return jQuery;
};


To use this with input fields, we can add the following in the jQuery(document).ready function:

$('input').bind('keyup', function(evt) {
  if (evt.keyCode == 40) {
      // down key
      $('input').elementAfter(this).focus();
  } else if (evt.keyCode == 38) {
      // up key
      $('input').elementBefore(this).focus();
  }
});

There you go, once the focus is in any input field, you can easily navigate to the previous/next one, using the up/down keys.

2 comments:

  1. I think this could annoy the users who use keys to slide up/down when browsing pages. You can accomplish the same result with Tab and Shift+Tab combinations.

    ReplyDelete
  2. Generally you might be right. Our scenario was a e-commerce platform with lists of entry fields and buttons. Using this, the user can switch between fields (below each other - up/down keys) and buttons (next to each field - tab/shift+tab) quickly. Of course this approch shouldn't be used on every single web-page...

    ReplyDelete