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.

4 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
  3. Thanks! just what I was looking for

    ReplyDelete
  4. Awesome, thanks for this. I rolled a custom one a long time ago for our point of sale at work, but this seems a bit more elegant.

    @Mathew Bukowicz, it completely depends on the scenario. For me, our sales guys are used to our old character system where you press 'enter' to go to the next form field, and you can use 'up/down' to go between them too.

    It is difficult to change people when they are so used to another method, and sometimes you just have to adapt, i have never heard any complaints from any of our customers who use our system to buy stuff off us either.

    ReplyDelete