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.