Shift focus with arrow keys in JavaScript

What I would do is much simpler. Just add a common class among the objects who should have this functionality (f.ex. "move") and use:

$(document).keydown(
    function(e)
    {    
        if (e.keyCode == 39) {      
            $(".move:focus").next().focus();

        }
        if (e.keyCode == 37) {      
            $(".move:focus").prev().focus();

        }
    }
);
​

See example: http://jsfiddle.net/uJ4PJ/

This code is much simpler and hopefully has all the functionality you need.

Just make sure the controls are in the correct order or this won't work properly.


After much trial and error, I developed this code that works :

function navigate(origin, sens) {
    var inputs = $('#form').find('input:enabled');
    var index = inputs.index(origin);
    index += sens;
    if (index < 0) {
        index = inputs.length - 1;
    }
    if (index > inputs.length - 1) {
        index = 0;
    }
    inputs.eq(index).focus();
}

$('input').keydown(function(e) {
    if (e.keyCode==37) {
        navigate(e.target, -1);
    }
    if (e.keyCode==39) {
        navigate(e.target, 1);
    }
});

right arrow acts as tab

left arrow acts as shift tab