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 < 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:
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.