Bhaskar
Bhaskar

Reputation: 31

Selecting the elements of a div using down arrow in autocomplete javascript

I am developing the autocomplete textbox where i populated the suggestions in a div in which each suggestion is a div with unique id.Now i want to select each suggestion using down arrow and also to highlight and bold the matched strings typed in the autosuggest textbox

For example in the following code

function displaySuggestions(suggestions){
  for(var i=0 ;i<suggestions.length ; i++){
    var div_display  = document.createElement('div');
    div_display.innerHTML = suggestions[i];
    div_display.className = "autosuggest_display_div";
    div_display.id = "autosuggest_display_div_"+i;        
    div.appendChild(div_display);        
}

Here div is the autosuggest div which contains the suggestions for each div..If I use the key press then whole div is highlighting instead of each div..as shown in following code

if(event.keyCode == '40'){
    for(var i=0;i<div.childNodes.length;i++){
      div.childNodes[i].style.background = "red";
}

Only on pressing down arrow of keyboard the only div should get highlighted

Upvotes: 1

Views: 1623

Answers (1)

alex
alex

Reputation: 490283

  • Look at keypress event.
  • Down arrow's key code is 40.
  • Add a class selected to each selected one, and use CSS to give it the desired highlight.

Upvotes: 2

Related Questions