Keyboard up and down arrows

rammohan picture rammohan · Nov 11, 2008 · Viewed 38k times · Source

I have one autocomplete search, in which by typing few characters it will show all the names, which matches the entered character. I am populating this data in the jsp using DIV tag, by using mouse I'm able to select the names. But I want to select the names in the DIV tag to be selected using the keyboard up and down arrow. Can anyone please help me out from this.

Answer

EndangeredMassa picture EndangeredMassa · Dec 17, 2008

Use the onkeydown and onkeyup events to check for key press events in your results div:

var UP = 38;
var DOWN = 40;
var ENTER = 13;

var getKey = function(e) {
  if(window.event) { return e.keyCode; }  // IE
  else if(e.which) { return e.which; }    // Netscape/Firefox/Opera
};


var keynum = getKey(e);

if(keynum === UP) {
  //Move selection up
}

if(keynum === DOWN) {
  //Move selection down
}

if(keynum === ENTER) {
  //Act on current selection
}