Reputation:
I have a text input. I want it this way - When the user presses the down arrow key, the focus should shift from the input to the first element in the list of divs below the input and keep moving downwards as we keep pressing the down key, and when the user presses the enter key the text in that div should be set as the input value. And vice versa for the up arrow key, i.e. if the user presses the up arrow key, the focus should shift to the last element in the list and keep moving upwards as we keep pressing the up key.
Here is the fiddle I created - Example
Upvotes: 0
Views: 173
Reputation: 1188
$(function(){
var $list = $('#list').children();
var index = 0;
function down(){
if(index == $list.length - 1) index = 0;
else index++;
move();
};
function up(){
if(index == 0) index = $list.length - 1;
else index--;
move();
};
function enter(){
var val = $($list[index]).html();
$('input').val(val);
};
function move()
{
$list.removeClass('highlight');
$($list[index]).addClass('highlight');
};
// highlights first element
move();
$('input').on('keydown', function(e){
switch(e.keyCode)
{
case 13:
enter();
break;
case 40:
down();
break;
case 38:
up();
break;
}
});
});
JSFiddle - http://jsfiddle.net/tt0nnzvm/4/
EDIT: Updated the fiddle and code
Upvotes: 0